2 回答

TA貢獻1942條經驗 獲得超3個贊
for正如您在評論中要求的示例一樣。
練習的重點似乎是在菜單上迭代,直到滿足退出條件 ( "X".equals(input))。這意味著在for語句中的三個條件之間,這是您唯一需要指定的條件。這是因為(基本)for陳述的一般形式是
for ( [ForInit] ; [Expression] ; [ForUpdate] )
括號之間的這些術語都不是強制性的,因此我們也可以去掉[ForInit]and [ForUpdate](但保留分號)。這具有不初始化任何東西的效果,[ForInit]并且在循環的每次迭代結束時什么也不做[ForUpdate],讓我們只檢查表達式給出的退出條件[Expression](當它被評估為時false,循環退出)。
請注意,console是在循環外聲明的,因為在每次迭代時都分配一個會很浪費。而且input,因為您在for聲明的條件下需要它。
Scanner console = new Scanner(System.in);
String input = "";
for (;!"X".equals(input);) { // notice, the first and last part of the for loop are absent
displayMenu();
input = console.nextLine().toUpperCase();
System.out.println();
switch (input) {
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
}
您可能會注意到這有點尷尬,因為這不是您通常使用for循環的目的。
無論如何,在這一點上,while版本變得微不足道 ( while (!"X".equals(input))) 并且在這種情況下,do...while也是等效的, ( do { ... } while (!"X".equals(input))) 因為相同的條件適用于當前循環的末尾和下一個循環的開始,并且有它們之間沒有副作用。
順便說一句,您可能會注意到while (condition)和for (; condition ;)在功能上是等效的,并且您可能會想知道為什么應該使用一個而不是另一個。答案是可讀性。做的時候想做什么就清楚多了while (condition)。

TA貢獻1829條經驗 獲得超9個贊
for 循環中的所有參數都不是強制性的。定義一個停止標志并檢查輸入是否為“X”。每當輸入是“X”時,只需更改 stopFlag 或只是簡單地使用 break 語句來中斷循環;
public void startFor()
{
boolean stopFlag = false;
for(; stopFlag == false ;) {
displayMenu();
Scanner console = new Scanner(System.in);
String input = console.nextLine().toUpperCase();
System.out.println();
switch (input)
{
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
if(input.contentEquals("X"))
stopFlag = true;
}
}
添加回答
舉報