如何检查输入是否为整数并重复,直到收到有效输入

时间:2015-10-14 09:59:22

标签: java validation

我有一个计算工资率的简单程序。我知道应该使用简单的while语句,但不确定如何才能最好地实现它。基本上所以我可以反复询问支付率,直到收到整数。

例如,如果用户输入“cat”,系统应显示警告消息并继续打印该消息,直到收到整数。

我有什么:

System.out.println("Please enter your hourly pay rate");
    if(user_input.hasNextInt()){
        payment = user_input.nextInt();
        System.out.println("Your hourly pay rate is " + payment + " dollars p/h");
    }
    else{
        System.out.println("Please enter a valid input");
    }

3 个答案:

答案 0 :(得分:0)

正如@Luke Park提到的那样,你可以

while(!user_input.hasNextInt()){
    System.out.println("Please enter a valid input");
}
payment = user_input.nextInt();
System.out.println("Your hourly pay rate is " + payment + " dollars p/h");

答案 1 :(得分:0)

使用带有无限循环的do-while循环。找到int值后,打破循环。使用try-catch处理其他输入的异常抛出。

    do {
      System.out.println("Please enter your hourly pay rate");
      String str = user_input.nextLine();
      try {
        payment = Integer.parseInt(str.trim());
        if (payment <= 0) {
          System.out.println("Please enter a valid input");
          continue;
        }
        System.out.println("Your hourly pay rate is " + payment + " dollars p/h");
        break;
      }
      catch (NumberFormatException e) {
        System.out.println("Please enter a valid input");
      }
    } while (true);

<强>输出:

Please enter your hourly pay rate
string
Please enter a valid input
Please enter your hourly pay rate
123
Your hourly pay rate is 123 dollars p/h

Online Demo

答案 2 :(得分:0)

我做了这个

    boolean gotIn = false;
    while (!gotIn) {
        try {
            System.out.print("Enter number ");
            Scanner scan = new Scanner(System.in);
            System.out.println(scan.nextInt());
            scan.close();
            gotIn = true;
        } catch (RuntimeException nfe) {
            System.err.println("Invalid input, Enter only numbers ");
        }
    }

但每次创建一个新的扫描仪,@ YoungHobbit解决方案都是正确的。