我最近开始学习Java,在测试某些东西时遇到了问题。这可能是一个非常简单的问题,但我似乎无法解决它。 这是我的代码:如果在while循环中,不能跳出while循环
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循环会中断并转到完成的字符串。如果你能用简单的代码帮助我解决这个问题,我将不胜感激,因为我不知道任何更先进的东西。
你的意思是你想突破* outer *循环吗? –
你正在打破内在,而不是外循环。所以虽然(真)永远是真的。 – Casey
“break”只能让你摆脱1循环。你最根本的问题是无限循环。有一个无限循环已经够糟了,你实际上有2个。现在是重构代码的时候了。 –