我最近开始学习 Java,在测试某些东西时遇到了一个问题。这可能是一个非常简单的问题,但我似乎无法解决。 这是我的代码:
int firstj = 1;
if (firstj == 1) {
String choice = "Type a number between 1 and 4";
System.out.println(choice);
while (true) {
if (firstj == 1) {
Scanner third = new Scanner(System.in);
String thirdch = third.nextLine();
while (true) {
if (thirdch.equals("1")) {
System.out.println("Show choice and accept input again ");
System.out.println(choice);
break;
} else if (thirdch.equals("2")) {
System.out.println("Show choice and accept input again ");
System.out.println(choice);
break;
} else if (thirdch.equals("3")) {
System.out.println("Show choice and accept input again ");
System.out.println(choice);
break;
}
else if (thirdch.equals("4")) {
// I need this to break the loop and move on to the
// "Done." string
break;
}
else {
System.out.println("Type a number between 1 and 4");
thirdch = third.nextLine();
}
}
}
}
}
String done = "Done";
System.out.println(done);
我想让它在您键入 1、2 或 3 时得到字符串,告诉您再次键入一个数字并接受用户输入,而当您键入 4 时,循环中断并转到 String done。如果你能用简单的代码帮助我解决这个问题,我将不胜感激,因为我不知道任何更高级的东西。
最佳答案
您可以标记循环,然后在 break 语句中使用该标签来指定要跳出哪个循环,例如
outer: while (true) {
while (true) {
break outer;
}
}
关于java - 如果在 while 循环内,则无法跳出 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32869552/