[英]How to escape this while-loop
我編寫了以下方法,該布爾返回類型再次分配給另一個方法中的另一個布爾,在該方法中我將此方法稱為該方法。
private boolean answer() {
Scanner input = new Scanner(System.in);
boolean b = false;
String answer = input.nextLine();
while(answer != "y" || answer != "n") {
System.out.println("Answer with y (yes) or n (no)");
answer = input.nextLine();
}
if (answer == "y") {
b = true;
}
return b;
}
但是無論我輸入什么(y,n或任何其他字母),我總是總是再次進入while循環。
這是因為您在測試中具有or
而不是and
。
正如目前所編碼的那樣,您在說:
當答案不是“ y” 或不是“ n”時,循環。
情況總是如此。
您想要的是:
答案不是“ y” 且不是“ n”時,循環。
編碼為:
while (answer != "y" && answer != "n") (
更改為: while(answer != "y" && answer != "n")
,您的代碼將按預期工作。
我懷疑您的問題出在這里:while(answer!=“ y” || answer!=“ n”)
當您的答案=“ y”時,它不是“ n”,因此循環繼續進行,反之亦然。
可能您想要這樣:while(answer!=“ y” && answer!=“ n”)
我稍微更改了您的代碼以接受一個char。
這是代碼:
private boolean answer() {
Scanner input = new Scanner(System.in);
boolean b = false;
char answer = input.nextLine().toLowerCase().charAt(0);
while(answer != 'y' || answer != 'n' ) {
System.out.println("Answer with y (yes) or n (no)");
//lower case so that it will get y or n, no matter what the casing is
answer = input.nextLine().toLowerCase().charAt(0);
}
if (answer == 'y') {
b = true;
}
return b;
}
或者如果您真的想要一個字符串
private boolean answer() {
Scanner input = new Scanner(System.in);
boolean b = false;
String answer = input.nextLine();
while( !(answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("n")) ) {
System.out.println("Answer with y (yes) or n (no)");
answer = input.nextLine();
}
if (answer.equalsIgnoreCase("y")) {
b = true;
}
return b;
}
比較兩個字符串時,請記住使用.equals()或.equalsIgnoreCase()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.