Java 如果在while循环中,可以';不要打破while循环
我最近开始学习Java,在测试一些东西时遇到了一个问题。这可能是一个非常简单的问题,但我似乎无法解决它。 这是我的代码:Java 如果在while循环中,可以';不要打破while循环,java,loops,if-statement,while-loop,break,Java,Loops,If Statement,While Loop,Break,我最近开始学习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)
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;
}
}
从描述中不太清楚,但是
continue
将允许您跳到循环的末尾,继续循环的其余部分,您可以使用标志来控制是否要退出多个级别。打破嵌套循环的最具伸缩性的方法是将整个内容放入一个函数中,然后使用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);
}
我希望这会有帮助。你的意思是想打破外环吗?你打破的是内部while循环,而不是外部while循环。所以,虽然(真的)总是真的,但“中断”只能让你脱离1个循环。你最基本的问题是无限循环。有一个无限循环已经够糟糕的了,实际上有两个循环。是时候重构你们的代码了。也许你们可以举出一些脆弱性的例子来提防?这种“未指明的坏处”很难被发现,直到它咬到你。我想芭丝谢芭只是想指出,当添加更多循环,代码变得更大、更复杂时,这种break语句的用法可能很难理解,我完全同意他的观点。@ChristopherYang和我并不反对:我真的记不起上次我用带标签的break是什么时候了;我认为通常有更简单的方法来构造代码以避免它。我的观点是,对于那些不熟悉它所产生的各种问题的人来说,描述说代码是脆弱的意味着什么是有用的。