我基本上想要以下while循环来检查输入是否是一个整数。它不能包含小数,因为它指向一个数组。如果输入的值是小数,它应该再次提示用户。问题是我在while循环以这段代码开始之前得到两个提示。有任何想法吗?检查如果从扫描仪输入是int与while循环java
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甚至两次虽然这是一个有效的值。
不起作用。无论输入是否有效,我最终都会得到无限循环的提示。 – Mo2
@ Mo2更新请看看 – Prabhaker