我已经在这个简单的问题上工作了好几个小时而没有到达任何地方。我试图验证输入到我的程序中的数字是在1到12之间。我已经尝试了几种循环,但得到了各种错误和问题,我在顶部的评论中详细说明了这些错误和问题。示例代码:
//This gives me an error saying that the local variable deptMonth may not have
//been initialized
boolean monthCorrect;
int deptMonth;
Scanner input = new Scanner(System.in);
do
{
System.out.print("Please input the month (1-12): ");
if (input.hasNextInt())
{
if ((input.nextInt()) <= 12 && (input.nextInt()) >=1)
{
deptMonth = input.nextInt();
monthCorrect = true;
}
else
{
System.out.println("I don't understand try again.");
monthCorrect = false;
input.next();
}
}
else
{
System.out.println("I don't understand try again.");
monthCorrect = false;
input.next();
}
}while (!(monthCorrect));
有没有更简单,更正确的方法呢?
谢谢。
答案 0 :(得分:0)
您反复调用方法nextInt
。这不会占用多个输入令牌吗?试试这个:只调用一次nextInt
并将其分配给变量,我们称之为foo
。然后测试foo
以查看它是否在正确的范围内,如果是,请将foo
分配给deptMonth
。
答案 1 :(得分:-1)
boolean monthCorrect;
int deptMonth;
Scanner input = new Scanner(System.in);
do
{
System.out.print("Please input the month (1-12): ");
if (input.hasNextInt())
{
int tmp = input.nextInt();
if ((tmp) <= 12 && (tmp) >=1)
{
deptMonth = tmp;
monthCorrect = true;
}
else
{
System.out.println("I don't understand try again.");
monthCorrect = false;
}
}
else
{
System.out.println("I don't understand try again.");
monthCorrect = false;
}
}while (!(monthCorrect));
此外,我不知道您是否继续输入,但最好在完成后关闭扫描仪,以防止内存问题等。
所以,
if ((tmp) <= 12 && (tmp) >=1)
{
deptMonth = tmp;
monthCorrect = true;
}
应该是这样的:
if ((tmp) <= 12 && (tmp) >=1)
{
deptMonth = tmp;
monthCorrect = true;
input.close();//This keeps everything tidy! Also eclipse should give you a warning message if you forget to include it!
}