[英]Exiting do-while loop with string input in java
我試圖寫下面的代碼,以便在輸入E時允許連續拋硬幣並退出。 不確定do-while循環是否是連續執行的正確方法,或者我應該使用其他方法。
do {
guess = sc.next();
tossGenerator(guess);
}while(!guess.equals("E")||!guess.equals("e"));
所以,我是否錯誤地使用了代碼,因為我無法擺脫do循環或者應該使用不同的方法。 請幫忙。 謝謝。
將&&
更改為||
:
} while (!guess.equals("E") && !guess.equals("e"));
或者像這樣重新排列:
} while (!(guess.equals("E") || guess.equals("e")));
或者,您可以使用String.equalsIgnoreCase()
並消除連接 :
} while (!guess.equalsIgnoreCase("e"));
將其更改為
while(!guess.equalsIgnoreCase("E") );
退出條件應該是AND運算符:
!guess.equals("E") && !guess.equals("e")
否則任何"E"
或"e"
都至少會使其中一個真實,因為如果它是“e”那么它不是“E”而反之亦然。
您的代碼的一個問題是,即使guess
為“e”,它也會調用tossGenerator(guess)
。 另一個是guess
總是不是“e”或不是“E”(它不能同時出現)。 我寫的是這樣的:
guess = sc.next();
while (!"e".equalsIgnoreCase(guess)) {
tossGenerator(guess);
guess = sc.next();
}
或者,使用for
循環:
for (guess = sc.next(); !"e".equalsIgnoreCase(guess); guess = sc.next()) {
tossGenerator(guess);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.