0

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());
          }   
      }   
  }   
newb
  • 77
  • 1
  • 2
  • 8
  • add `sc.nextLine()` after your while in your if – Duffydake Mar 24 '15 at 16:05
  • It still does not work. I still have the same problem – newb Mar 24 '15 at 16:07
  • `while (sc.hasNextInt())` will wait until you've got something else than an integer. call `sc.nextInt()` twice instead. If you can have more than 2 integer then use sc.nextLine() and split it. – Duffydake Mar 24 '15 at 16:09

2 Answers2

0

From http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block.

Guest
  • 1
0

replace

   while (sc.hasNextInt()){
     stack.push(sc.nextInt());
   } 

with

stack.push(sc.nextInt());
stack.push(sc.nextInt());

also you don't need sc.nextLine(); at end

see hasNext() - when does it block and why?

Community
  • 1
  • 1
M Sach
  • 33,416
  • 76
  • 221
  • 314