使用while循环java检查来自扫描仪的输入是否为int [英] checking if input from scanner is int with while loop java
本文介绍了使用while循环java检查来自扫描仪的输入是否为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我基本上想要以下 while 循环来检查输入是否为整数.它不能包含小数,因为它指向一个数组.如果输入的值是小数,它应该再次提示用户.问题是在使用此代码开始 while 循环之前,我收到了两个提示.有什么想法吗?
I basically want the following while loop to check if the input is an integer. It cannot contain decimals because it is pointing to an array. If the value entered is a decimal it should prompt the user again. Problem is I get two prompts before the while loop starts with this code. Any ideas?
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();
}
谢谢
当前输出提供以下内容:
The current output gives the following:
Enter month (valid values are from 1 to 12): 2
2
请注意,即使 2 是有效值,我也必须输入两次.
Notice how I had to enter 2 twice even though it is a valid value.
推荐答案
对你的程序稍作修改即可解决问题
A small modification to your program solves the problem
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
希望对你有帮助.
这篇关于使用while循环java检查来自扫描仪的输入是否为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文