I keep getting; The stack is: StackOfIntegers@55f96302 9 8 7 6 5 4 3 2 1 0 How d
ID: 3785308 • Letter: I
Question
I keep getting;
The stack is: StackOfIntegers@55f96302
9 8 7 6 5 4 3 2 1 0
How do I get rid of the bolded area above when printing my stack??
J StackOf Integers java TestStackoflntegers,java 1 import java util 2 public class Teststac kofIntegers f 3e public static void main (String[] args) t Stac rs stack new Stac kofIntegers Scanner sc new Scanner (system. in for (int i 0; i 10 i++) stack push (i) 10 System.out.println("Please enter a number for operation: 11 System out.println("(1) Push") 12 System out.println("(2) Pop") 13 System. out.println("(3) View Stac System. out.println(" (4) Exit"); k") 14 15 16 int input sc 17 18 (input 4 II input 1) if 19 system out.println("ERROR: Enter a valid option 20 System exit (0); 21 22 elset 23 if (input 1) 24 System out.println("Please enter a number to be pushed"); 25 int pushNum SC nextInt 26 stack push (push Num) 27 28 else if (input 2)t 29 System ed object is stack pop()) 30 31 else if (input 3)t 32 system. out.println The stack is stack) 33 34 else{ 35 System.out.println( Program will now terminate 36 System exit (0); 37 38 39 while (!stack. empty System.out.print (stack pop 43Explanation / Answer
You didn't provided the code for StackOfIntegers.java. Actually, the error is not in the tester but is in the other part StackOfIntegers.java.
Here, you're trying to print the object stack of type StackOfIntegers in case 3, using the statement, System.out.println("The stack is " + stack);
To print an object, you should overwrite the toString() object in the class.
So, try adding this method in your StackOfIntegers.java class:
public String toString()
{
String output = "";
//And here use a loop to print the elements of the stack, based on the datastructure you used, without actually popping them, and add them to the string output, separated by spaces.
return output;
}
This will do the trick for you.
If you couldn't sort it out, please update the StackOfIntegers.java class along with this class, so that I will help you out on that. And also, when providing code, please copy and paste the code, instead of uploading images, so that we can reuse the same, and give you a quick solutions.