【问题标题】:Scanner keeps skipping input whist using nextInt() and loops扫描仪使用 nextInt() 和循环不断跳过输入whist
【发布时间】:2013-03-09 02:29:51
【问题描述】:

我正在使用 while 循环来确保输入到扫描仪对象的值是这样的整数:

while (!capacityCheck) {
        try {
            System.out.println("Capacity");
            capacity = scan.nextInt();
            capacityCheck = true;
        } catch (InputMismatchException e) {
            System.out.println("Capacity must be an integer");
        }
    }

但是,如果用户没有输入整数,当它应该返回并接受另一个输入时,它只会重复打印“Capacity”,然后在 catch 中输出,而不要求更多输入。我该如何阻止这种情况?

【问题讨论】:

    标签: java loops java.util.scanner next


    【解决方案1】:
    scan.nextLine();
    

    将这段代码放入您的catch 块中,以消耗非整数字符以及留在缓冲区中的换行符(因此,无限打印catch sysout),如果您已经输入错误。

    当然,还有其他更简洁的方法可以实现您想要的,但我想这需要对您的代码进行一些重构。

    【讨论】:

    • 为什么放scan.nextLine();
    • scan.nextInt() 将只扫描下一个整数,但是当它不是正确的输入时,输入的无效字符会停留在那里,不会被消耗,因此会使 while 进入无限循环。更新了我的答案! :)
    【解决方案2】:

    我认为不需要 try/catch 或 capacityCheck,因为我们可以访问方法 hasNextInt() - 它检查下一个令牌是否是 int。例如,这应该做你想做的事:

        while (!scan.hasNextInt()) { //as long as the next is not a int - say you need to input an int and move forward to the next token.
            System.out.println("Capacity must be an integer");
            scan.next();
        }
        capacity = scan.nextInt(); //scan.hasNextInt() returned true in the while-clause so this will be valid.
    

    【讨论】:

      【解决方案3】:

      试着把它放在循环的末尾 -

      scan.nextLine();
      

      或者最好把它放在 catch 块中。

          while (!capacityCheck) {
              try {
                  System.out.println("Capacity");
                  capacity = scan.nextInt();
                  capacityCheck = true;
              } catch (InputMismatchException e) {
                  System.out.println("Capacity must be an integer");
                  scan.nextLine();
              }
          }
      

      【讨论】:

      • 需要消耗换行符。
      【解决方案4】:

      试试这个:

      while (!capacityCheck) {
          try {
              System.out.println("Capacity");
              capacity = scan.nextInt();
              capacityCheck = true;
          } catch (InputMismatchException e) {
              System.out.println("Capacity must be an integer");
              scan.nextLine();
          }
      }
      

      【讨论】:

        【解决方案5】:

        使用以下内容:

        while (!capacityCheck) {
                System.out.println("Capacity");
                String input = scan.nextLine();
                try {
                    capacity = Integer.parseInt(input );
                    capacityCheck = true;
                } catch (NumberFormatException e) {
                    System.out.println("Capacity must be an integer");
                }
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-12-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多