Hi I have a problem getting out of the loop. My input (it can input any number of integer) supposed to be
Add 10 5 //input then after I press enter it supposed to show the output
Items added: [5, 10] //output
But instead I get
Add 10 5 //enter
Add 2 //I need to enter another input to get the output
Items added: [5, 10] //output
Here is my code. I think the problem is after the while loop I need to remove the remainder of the input line but I don't know how to fix it. Please help, thank you
public static void main(String [] args) throws NoSuchElementException {
StackLL <Integer> stack = new StackLL <Integer> ();
Scanner sc = new Scanner(System.in);
String op;
while (sc.hasNext()) {
op = sc.next();
if (op.equals("Add")) {
// Fill in the code
while (sc.hasNextInt()){
stack.push(sc.nextInt());
}
System.out.print("Items added: ");
System.out.print(stack.toString() + "\n");
}
else if (op.equals("Query")) {
// Fill in the code
while (sc.hasNextInt()) {
int query = sc.nextInt();
int pop = query - 1;
while (query!=pop)
pop = stack.pop();
}
sc.nextLine();
System.out.println("Query met: " + stack.toString());
}
}
}