检查来自scanner的输入是否与while循环java一致

时间:2013-08-01 05:03:08

标签: java while-loop

我基本上想要以下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两次,即使它是有效值。

3 个答案:

答案 0 :(得分:3)

在致电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;
    }
}

答案 1 :(得分: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,以便在有效输入后退出。

答案 2 :(得分: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

希望这会对你有所帮助。