[英]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.