A. Set up the compiler on your workstation. B. Write/modify, compile, and run th
ID: 3547062 • Letter: A
Question
A. Set up the compiler on your workstation.
B. Write/modify, compile, and run the attached Java program(entitled "BabyElephantWalk") so that
the program:
(1) uses a single line comment to document your name and section number. This should be
the very first line of your program,
(2) uses a println statement to print your name and section number as the first line your output,
(3) prompts the user to type a name for an elephant,
(4) adds the name of this elephant to the list of elephants in the baby elephant walk.
(5) creates a user defined function to delete an elephant from the list. Then use this delete
function to delete
Explanation / Answer
import javax.swing.JOptionPane;
class Elephant {
private String title;
public Elephant(String newname) {
title = newname;
}//end Elephant constructor
public String toString() {
return title;
}
}
public class ElephantList {
private ElephantNode list;
public ElephantList() {
list = null;
}//end ElephantList constructor
public void add(Elephant cat) {
ElephantNode node = new ElephantNode(cat);
ElephantNode current;
if (list == null) {
list = node;
} else {
current = list;
while (current.next != null) {
current = current.next;
}
current.next = node;
}
}//end add
public void delete(Elephant name)
{
ElephantNode node=new ElephantNode(name);
ElephantNode current;
if(list==null)
System.out.println("Empty");
else
{
current = list;
while(current.elephant!=name)
{
current=current.next;
}
current.next = current.next.next;
}
}
public String toString() {
String result = "";
ElephantNode current = list;
while (current != null) {
result += current.elephant + " ";
current = current.next;
}
return result;
}//end toString
private class ElephantNode {
public Elephant elephant;
public ElephantNode next;
public ElephantNode(Elephant cat) {
elephant = cat;
next = null;
}//end ElephantNode constructor
}//ElephantNode
}//end ElephantList
class BabyElephantWalk {
public static void main(String[] args) {
System.out.println("Abhishek " + " Roll number ");
ElephantList walk = new ElephantList();
walk.add(new Elephant("Charlie"));
walk.add(new Elephant("Donna"));
walk.add(new Elephant("Chilli"));
walk.add(new Elephant("Piper"));
walk.add(new Elephant("Ziva"));
String name = JOptionPane.showInputDialog("Enter name of an elephant");
walk.add(new Elephant(name));
System.out.println(walk);
walk.delete(new Elephant("Charlie"));
System.out.println(walk);
name = JOptionPane.showInputDialog("Enter name of an elephant to delete");
walk.delete(new Elephant(name));
System.out.println(walk);
}
}