2 回答

TA貢獻(xiàn)1942條經(jīng)驗(yàn) 獲得超3個(gè)贊
for正如您在評(píng)論中要求的示例一樣。
練習(xí)的重點(diǎn)似乎是在菜單上迭代,直到滿足退出條件 ( "X".equals(input))。這意味著在for語(yǔ)句中的三個(gè)條件之間,這是您唯一需要指定的條件。這是因?yàn)椋ɑ荆ゝor陳述的一般形式是
for ( [ForInit] ; [Expression] ; [ForUpdate] )
括號(hào)之間的這些術(shù)語(yǔ)都不是強(qiáng)制性的,因此我們也可以去掉[ForInit]and [ForUpdate](但保留分號(hào))。這具有不初始化任何東西的效果,[ForInit]并且在循環(huán)的每次迭代結(jié)束時(shí)什么也不做[ForUpdate],讓我們只檢查表達(dá)式給出的退出條件[Expression](當(dāng)它被評(píng)估為時(shí)false,循環(huán)退出)。
請(qǐng)注意,console是在循環(huán)外聲明的,因?yàn)樵诿看蔚鷷r(shí)都分配一個(gè)會(huì)很浪費(fèi)。而且input,因?yàn)槟趂or聲明的條件下需要它。
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;
}
}
您可能會(huì)注意到這有點(diǎn)尷尬,因?yàn)檫@不是您通常使用for循環(huán)的目的。
無(wú)論如何,在這一點(diǎn)上,while版本變得微不足道 ( while (!"X".equals(input))) 并且在這種情況下,do...while也是等效的, ( do { ... } while (!"X".equals(input))) 因?yàn)橄嗤臈l件適用于當(dāng)前循環(huán)的末尾和下一個(gè)循環(huán)的開(kāi)始,并且有它們之間沒(méi)有副作用。
順便說(shuō)一句,您可能會(huì)注意到while (condition)和for (; condition ;)在功能上是等效的,并且您可能會(huì)想知道為什么應(yīng)該使用一個(gè)而不是另一個(gè)。答案是可讀性。做的時(shí)候想做什么就清楚多了while (condition)。

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超9個(gè)贊
for 循環(huán)中的所有參數(shù)都不是強(qiáng)制性的。定義一個(gè)停止標(biāo)志并檢查輸入是否為“X”。每當(dāng)輸入是“X”時(shí),只需更改 stopFlag 或只是簡(jiǎn)單地使用 break 語(yǔ)句來(lái)中斷循環(huán);
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;
}
}
添加回答
舉報(bào)