这是我第一次在这里发帖,所以如果格式不好,我道歉。我的应用程序旨在要求用户输入我的一个室友姓名,该应用程序将输出有关该室友的信息。然后,它应该询问用户是否要继续。我希望它只能接受'y‘或'n’。当它问我是否要继续时,我输入一个字母,而不是'y‘或'n’,它会正确地要求我输入一个可接受的答案。然而,如果我输入了'y‘或'n’,它就好像我只输入了一次不可接受的答案,然后就做了它应该做的事情。任何帮助都是非常感谢的。
package roomateapp;
import java.util.Scanner;
public class RoomateApp {
public static void main(String[] args) {
//Initialize scanner to take in roomate name
Scanner sc = new Scanner(System.in);
String cont = "y";
while (cont.equalsIgnoreCase("y")) {
//CODE HERE BUT NOT SHOWN
//Ask to continue
System.out.println("Would you like to continue? (y/n)");
cont = sc.next();
System.out.println();
if (!cont.equalsIgnoreCase("y") || !cont.equalsIgnoreCase("n")) {
while (!cont.equalsIgnoreCase("y") || !cont.equalsIgnoreCase("n")) {
System.out.println("Please enter 'y' or 'n'");
System.out.println("Would you like to continue? (y/n)");
cont = sc.next();
if (cont.equalsIgnoreCase("y") || cont.equalsIgnoreCase("n")) {
break;
}
}
} else {
}
System.out.println();
}
}
}
发布于 2018-09-21 05:40:52
你为什么不检查一下你有没有"y“或"n",而不是检查你没有什么呢?
我会将cont
初始化为null
或其他标记值,然后在cont
保持不变的情况下循环。当您在循环内部验证用户给出的值是"y“或"n”时,我只会为cont
赋值。
Scanner sc = new Scanner(System.in);
System.out.println("Would you like to continue? (y/n)");
String cont = null;
while(cont == null) {
String unvalidatedString = sc.next();
if (unvalidatedString.equalsIgnoreCase("y")) {
cont = unvalidatedString;
break;
}
if (unvalidatedString.equalsIgnoreCase("n")) {
cont = unvalidatedString;
break;
}
System.out.println("Please enter 'y' or 'n'");
}
// This is just added as a test case for you to verify that it's working. Remove from production code.
System.out.printf("The value of cont is: %s\n", cont);
https://stackoverflow.com/questions/52433441
复制相似问题