[英]If inside a while loop, can't break out of the while loop
我最近开始学习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时,循环中断并转到完成字符串。 如果你能用一个简单的代码帮助我解决这个问题,我将不胜感激,因为我不知道任何更高级的东西。
您可以标记循环,然后在break语句中使用标签来指定要打破的循环,例如
outer: while (true) {
while (true) {
break outer;
}
}
打破嵌套循环的最可扩展的方法是将整个事物放在一个函数中并使用return
。
在Java中打破标签是另一种选择,但它可能会使代码变得脆弱:你可能会受到一些顽固的重构者的摆布,他们可能会倾向于将“破坏标签”移动到幸福地意识不到后果; 编译器无法警告这样的恶作剧。
您可以使用锁定停止,如下所示:
public static void main(String[] args) throws Exception {
int firstj = 1;
if (firstj == 1) {
boolean lock = true;
while (lock) {
if (firstj == 1) {
Scanner third = new Scanner(System.in);
while (lock) {
System.out.println("Type a number between 1 and 4");
String thirdch = third.nextLine();
switch (thirdch) {
case "1":
System.out
.println("Show choice and accept input again ");
break;
case "2":
System.out
.println("Show choice and accept input again ");
break;
case "3":
System.out
.println("Show choice and accept input again ");
break;
case "4":
lock = false;
break;
}
}
third.close();
}
}
}
String done = "Done";
System.out.println(done);
}
我希望它有所帮助。
从描述中不太清楚,但是continue
将让你跳到循环结束,继续循环的其余部分,你可以使用标志来控制你是否要退出多个级别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.