Question: How to test the display method without getting an infinite loop. This is the question: Suppose that the ADT stack included the void method display,
How to test the display method without getting an infinite loop.
This is the question: Suppose that the ADT stack included the void method display, which displays the entries in a stack. Implement this method for each of the following classes: LinkedStack, as outlined in Listing 6-1. Please make sure that the method uses T generic type and print "Stack is empty" if the stack doesn't have anything.
The method used:
public void display() { if(!isEmpty()){ Node ptr=topNode;
while(ptr.getNextNode()!=null) { System.out.println(ptr.getData()+" "); } System.out.println(); } }
When I use it in my main method to test it I get an infinite loop display of the last item added in the stack. This is the main:
public class Driver { public static void main(String[] args) { System.out.println("Create a stack: "); //myStack is a reference variable with type StackInterface, this means that we can only call the methods in the //StackInterface on myStack variable StackInterface
System.out.println(" isEmpty() returns " + myStack.isEmpty());//F
System.out.println(" Testing peek and pop:"); while (!myStack.isEmpty()) { String top = myStack.peek();//call peek to return the data in the topNode to top variable System.out.println(" " + top + " is at the top of the stack.");//print the value of top top = myStack.pop();//delete the first node System.out.println(top + " is removed from the stack."); //see that the node that has been removed is //the same as was peeked } // end while
System.out.print(" The stack should be empty: "); System.out.println("isEmpty() returns " + myStack.isEmpty());//T
System.out.println(" Add to stack to get " + "Jim Jess Joe "); myStack.push("Joe"); myStack.push("Jess"); myStack.push("Jim");//Jim Jess Joe System.out.println(" Testing clear:"); myStack.clear();//makes the topNode = null System.out.println("The stack should be empty: "); System.out.println(" isEmpty() returns " + myStack.isEmpty());//T
System.out.println(" myStack.peek() returns "); System.out.println(myStack.peek()); //Exception because stack is empty System.out.println(" myStack.pop() returns "); //Exception because stack is empty System.out.println(myStack.pop()); } // end testStackOperations } // end Driver
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
