Java 使用 while 循环作为输入验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18906267/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:11:52  来源:igfitidea点击:

Using while loop as input validation

java

提问by Flow

I'm trying to use while loop to ask the user to reenter if the input is not an integer

如果输入不是整数,我正在尝试使用 while 循环要求用户重新输入

for eg. input being any float or string

例如。输入是任何浮点数或字符串

      int input;

      Scanner scan = new Scanner (System.in);

      System.out.print ("Enter the number of miles: ");
      input = scan.nextInt();
      while (input == int)  // This is where the problem is
          {
          System.out.print("Invalid input. Please reenter: ");
          input = scan.nextInt();
          }

I can't think of a way to do this. I've just been introduced to java

我想不出办法做到这一点。我刚刚被介绍到java

回答by ATG

The issue here is that scan.nextInt()will actually throw an InputMismatchExceptionif the input cannot be parsed as an int.

这里的问题是,scan.nextInt()实际上会抛出一个InputMismatchException如果输入不能被解析为一个int

Consider this as an alternative:

将此视为替代方案:

    Scanner scan = new Scanner(System.in);

    System.out.print("Enter the number of miles: ");

    int input;
    while (true) {
        try {
            input = scan.nextInt();
            break;
        }
        catch (InputMismatchException e) {
            System.out.print("Invalid input. Please reenter: ");
            scan.nextLine();
        }
    }

    System.out.println("you entered: " + input);

回答by Aaron

The javadocs say that the method throws a InputMismatchException if the input doesn;t match the Integer regex. Perhaps this is what you need?

javadocs 说如果输入不匹配整数正则表达式,该方法会抛出 InputMismatchException 。也许这就是你所需要的?

So...

所以...

int input = -1;
while(input < 0) {
  try {
     input = scan.nextInt();
  } catch(InputMismatchException e) {
    System.out.print("Invalid input. Please reenter: ");
  }
}

as an example.

举个例子。