我需要编写代码以针对不同的输出返回两条不同的错误消息。 一个表示用户输入为空,另一个表示用户输入不是 y 或 n。我遇到的问题是我的代码只返回非 y 或 n 的错误消息,因为如果用户输入 y 或 n 以外的任何内容,我将返回该消息。该代码将为空白错误返回一次正确的错误消息,但之后会卡住,只返回非 y 或 n 的错误消息。关于如何解决这个问题有什么建议吗?
while (choice.isEmpty())
{
System.out.println("Error! This entery is required. Try again.");
choice = sc.nextLine();
}
while (!(choice.equalsIgnoreCase ("y") || choice.equalsIgnoreCase ("n")))
{
System.out.println ("Error! Please enter y, Y, n, or N. Try again ");
choice = sc.nextLine();
}
最佳答案
您可能最好使用一个循环:
while (!choice.equalsIgnoreCase("y") && !choice.equalsIgnoreCase("n")) {
if (choice.isEmpty()) {
System.out.println("Error! This entry is required. Try again.");
} else {
System.out.println("Error! Please enter y, Y, n, or N. Try again.");
}
choice = sc.nextLine();
}
关于java - 我的循环在 Java 中设置正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42239543/