不知怎的,我在这里得到了一些有趣的游戏,但我就是不明白为什么。
此方法应该确保输入是 y 或 n,并且不为空。 我应该注意这是为了学校,并且需要 2 个单独的错误输出。
当我输入一个空行时,我在控制台上得到的正是一个空行。 在那之后,或者在我故意输入错误数据(例如 x)之后,下次我输入有效数据(例如 y 或 n)时,我会继续在无限循环中获取错误数据。
我做错了什么?
public static boolean getContinue(Scanner sc)
{
boolean decision = false;
System.out.println("Continue? Y/N: ");
String userChoice = sc.next();
boolean isValid = false;
while (isValid == false)
{
if (userChoice.equalsIgnoreCase("y"))
{
decision = true;
isValid = true;
}
else if (userChoice.equalsIgnoreCase("n"))
{
decision = false;
isValid = true;
}
else if (userChoice.equals(""))
{
System.out.println("Error! This entry is required. Try again.");
userChoice = sc.next();
}
else if (!userChoice.equalsIgnoreCase("y") | (!userChoice.equalsIgnoreCase("n")))
{
System.out.println("Error! Entry must be 'Y' or 'N'. Try again.");
userChoice = sc.next();
}
}
return decision;
}
注意: 代码已修改为包括
新的控制台输出(仍然错误)
格式化结果 贷款金额:$5.00 年利率:500% 年数:5 每月付款:2.08 美元
继续吗?是/否:
b 错误!输入必须是“Y”或“N”。再试一次。 y 错误!输入必须是“Y”或“N”。再试一次。 y 输入贷款金额:
最佳答案
您没有将变量 userChoice 设置为新值。将最后一个 if 子句更改为
System.out.println("Error! Entry must be 'Y' or 'N'. Try again.");
userChoice = sc.next();
关于Java方法在验证输入时陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21821542/