我有點堅持我必須做的練習,我想不出最好的方法。
我必須創建一個提出問題并期望 Y 或 N 的方法。所以我想我會創建一個布爾方法來回傳 true 或 false,但問題是如果用戶輸入 Y 或以外的其他內容,它也會回傳 false N. 如果我沒記錯的話,布爾方法不能回傳 null。
我對java很陌生,而且我的課程也不是很遠,所以這個問題可能會有一個非常簡單的解決方案。我也嘗試尋找答案,但似乎沒有找到我想要的東西。
這就是我對布爾方法的看法,但我對它不太滿意:
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String reponse = sc.next();
if (reponse.equalsIgnoreCase("Y")) {
return true;
}
else if (reponse.equalsIgnoreCase("N")) {
return false;
}
else {
return false;
}
}
uj5u.com熱心網友回復:
你只需要一個條件equalsIgnoreCase("Y"),它的評估結果基本上就是回傳值。代碼中的所有if- 陳述句都是多余的。
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String reponse = sc.next();
return reponse.equalsIgnoreCase("Y"));
}
uj5u.com熱心網友回復:
根據您的評論,如果輸入既不是“y”也不是“n”,您希望程式再次要求輸入。您可以通過添加一個額外的回圈來實作該行為:
public static boolean test() {
Scanner sc = new Scanner(System.in);
System.out.println("question");
String response = sc.next();
while(!response.equalsIgnoreCase("Y") && !response.equalsIgnoreCase("N")) {
// loop as long as input is neither "y" nor "n" (ignoring case)
System.out.println("Please enter 'y' or 'n'");
reponse = sc.next();
}
// if the loop is done input has to be either "y" or "n" at this point
return reponse.equalsIgnoreCase("y");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/521543.html
標籤:爪哇布尔值
