0

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

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

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

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

4

2 回答 2

1

这里的问题是,scan.nextInt()如果InputMismatchException输入不能被解析为int.

考虑将此作为替代方案:

    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);
于 2013-09-19T23:10:14.863 回答
1

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

所以...

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

举个例子。

于 2013-09-19T23:10:22.823 回答