走出While(hasNextInt())

时间:2015-03-24 15:58:43

标签: java loops while-loop

嗨,我有一个问题退出循环。我的输入(它可以输入任意数量的整数)应该是

Add 10 5 //input then after I press enter it supposed to show the output
Items added: [5, 10] //output

但我得到了

Add 10 5 //enter
Add 2 //I need to enter another input to get the output
Items added: [5, 10] //output

这是我的代码。我认为问题是在while循环后我需要删除输入行的其余部分,但我不知道如何解决它。请帮忙,谢谢

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());
          }   
      }   
  }   

2 个答案:

答案 0 :(得分:0)

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

next()和hasNext()方法及其原始类型的伴随方法(例如nextInt()和hasNextInt())首先跳过与分隔符模式匹配的任何输入,然后尝试返回下一个标记。 hasNext和next方法可能阻止等待进一步输入。 hasNext方法块是否与其关联的下一个方法是否将阻止无关。

答案 1 :(得分:0)

替换

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

<强>与

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

你最后还不需要sc.nextLine();

请参阅hasNext() - when does it block and why?