使用while循环作为输入验证

时间:2013-09-19 22:57:12

标签: java

我正在尝试使用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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

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

因此...

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

作为一个例子。