【问题标题】:Using while loop as input validation [duplicate]使用while循环作为输入验证[重复]
【发布时间】:2013-09-25 05:19:30
【问题描述】:

如果输入不是整数,我正在尝试使用 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

【问题讨论】:

  • 看看Scanner.hasNext 方法。在那里您可以确定下一个输入是哪种类型。

标签: java


【解决方案1】:

这里的问题是,如果输入无法解析为 intscan.nextInt() 实际上会抛出 InputMismatchException

将此作为替代方案:

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

【讨论】:

    【解决方案2】:

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

    所以...

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

    举个例子。

    【讨论】:

    • Except -1 就您而言可能是一个有效数字。我下面的答案会起作用。
    • 仅供参考:根据选项卡中看到的编辑和用户设置(即最旧的,...),“下面”很快失去了意义。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 2021-05-13
    • 2018-04-08
    • 2016-05-27
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多