Not able to add multiple elements inside the stack in java collection framework. whenever i print the stack then also the stack is showing the currently added element inside the stack. I am trying to add multiple elements inside the stack so that i can perform all stack related operations.
import java.util.*;
public class stackexp1 {
public static void main(String[] args) {
while (true) {
Stack<Integer> numberss = new Stack<Integer>();
System.out.println("\n.........Operations on stack ...........");
System.out.println("1 >> Push >> 1 ");
System.out.println("2 >> Pop >> 2 ");
System.out.println("3 >> Display >> 3 \n");
int choice, num;
System.out.print("Enter your choice >> ");
Scanner sdc = new Scanner(System.in);
choice = sdc.nextInt();
switch (choice) {
case 1: {
System.out.println("Your choice was push operation ......:)");
System.out.print("\nEnter a number to be pushed >> ");
Scanner b = new Scanner(System.in);
num = b.nextInt();
numberss.push(num);
System.out.println(numberss);
}
break;
case 2: {
if (numberss.size() >= 0) {
System.out.println("Your choice is pop operation ......:)");
System.out.println("The element from the stack >> " + numberss.pop());
} else {
System.out.println("\nStack is empty");
}
}
break;
case 3: {
if (numberss.size() >= 0) {
System.out.println("Your choice is display Stack elements .....:)");
System.out.println("The elements inside the stack are >> " + numberss);
} else {
System.out.println("Stack is empty ....:)");
}
}
break;
default: {
System.out.println("No such choice is available ....:)");
}
}
}
}
}
Output .. >>
>Solution :
That is because you are creating a new stack on each iteration of the while loop.
Move the declaration and initialization of the stack outside the while loop. Also, you don’t need more than one instance of a Scanner
. You can move that outside the loop as well.
Stack<Integer> numbers = new Stack<>();
Scanner sdc = new Scanner(System.in);
while (true) {
// your logic
}