-1

我基本上想要以下while循环来检查输入是否为整数。它不能包含小数,因为它指向一个数组。如果输入的值是小数,它应该再次提示用户。问题是在 while 循环从此代码开始之前我得到两个提示。有任何想法吗?

      System.out.print("Enter month (valid values are from 1 to 12): ");
    Scanner monthScan = new Scanner(System.in);
    int monthInput = monthScan.nextInt();
    // If the month input is below 1 or greater than 12, prompt for another value
    while(monthInput<1 || monthInput>12 || !monthScan.hasNextInt())
    {
        System.out.print("Invalid value! Enter month (valid values are from 1 to 12): ");
        monthInput = new Scanner(System.in).nextInt();
    }

谢谢

编辑:当前输出给出以下内容:

Enter month (valid values are from 1 to 12): 2
2

请注意,即使 2 是有效值,我也必须输入两次。

4

3 回答 3

4

hasNextInt()在调用之前检查输入是否为整数nextInt()。否则当用户键入非整数时nextInt()抛出。InputMismatchException

int monthInput;

System.out.print("Enter month (valid values are from 1 to 12): ");
Scanner monthScan = new Scanner(System.in);

if (monthScan.hasNextInt()) {
    monthInput = monthScan.nextInt();
} else {
    monthScan.next();   // get the inputted non integer from scanner
    monthInput = 0;
}

// If the month input is below 1 or greater than 12, prompt for another value
while (monthInput < 1 || monthInput > 12) {
    System.out.print("Invalid value! Enter month (valid values are from 1 to 12): ");
    if (monthScan.hasNextInt()) {
        monthInput = monthScan.nextInt();
     } else {
       String dummy = monthScan.next();
       monthInput = 0;
    }
}
于 2013-08-01T06:39:42.073 回答
2

你可以这样检查

System.out.print("Enter month (valid values are from 1 to 12): ");
Scanner monthScan = new Scanner(System.in);

while(monthScan.hasNext())
{
   if(!monthScan.hasNextInt() && (monthInput<1 ||  monthInput>12))
   {
       System.out.print("Invalid value! Enter month (valid values are from 1 to 12):"); 
       continue;
   }

   // If the month input is below 1 or greater than 12, prompt for another value
  int monthInput = monthScan.nextInt();
  //do your logic here   
  break;//use the break after logic 

}

更新
在您的逻辑之后 使用break,以便在有效输入后退出。

于 2013-08-01T05:12:36.710 回答
1

对您的程序稍作修改即可解决问题

 System.out.print("Enter month (valid values are from 1 to 12): ");
        Scanner monthScan = new Scanner(System.in);
       int monthInput = monthScan.nextInt();
        // If the month input is below 1 or greater than 12, prompt for another value
        while((monthInput<1 || monthInput>12) )
        {
            System.out.print("Invalid value! Enter month (valid values are from 1 to 12): ");

            monthInput = monthScan.nextInt();
        }
        System.out.println("I am here");

输出:

Enter month (valid values are from 1 to 12): -5
Invalid value! Enter month (valid values are from 1 to 12): -5
Invalid value! Enter month (valid values are from 1 to 12): -2
Invalid value! Enter month (valid values are from 1 to 12): 5
I am here

希望这对您有所帮助。

于 2013-08-01T06:29:56.330 回答