有人能告訴我如何將錯誤消息放入以下代碼嗎?如果用戶輸入的數字不在0到12之間,我該如何輸出「無效輸入」。如何顯示錯誤信息
此時程序正常工作,如果輸入了無效字符,用戶可以再次嘗試。
int hours;
do {
System.out.print("Enter hours: ");
hours = myscanner.nextInt();
} while (hours < 0 || hours > 12);
有人能告訴我如何將錯誤消息放入以下代碼嗎?如果用戶輸入的數字不在0到12之間,我該如何輸出「無效輸入」。如何顯示錯誤信息
此時程序正常工作,如果輸入了無效字符,用戶可以再次嘗試。
int hours;
do {
System.out.print("Enter hours: ");
hours = myscanner.nextInt();
} while (hours < 0 || hours > 12);
int hours;
boolean valid;
do {
System.out.print("Enter hours: ");
hours = myscanner.nextInt();
valid = (hours >= 0 && hours <= 12);
if (!valid)
System.out.println("Invalid entry");
} while (!valid);
注:我添加了一個變量,因爲否則的話,你就必須重複的條件有 NOTE2:我也恢復了狀態,因爲如果布爾值指的是我不喜歡負狀態(我更喜歡在有效無效)
爲什麼downvote? – Cruncher
克朗徹:我寫了幾個拼寫錯誤,因此有一段時間,當答案中有完整的亂碼時 – NeplatnyUdaj
請不要讓我失望!我有666個SO點:) – NeplatnyUdaj
int hours;
do {
System.out.print("Enter hours: ");
hours = myscanner.nextInt();
if (hours < 0 || hours > 12) System.out.println("Please insert a valid entry");
} while (hours < 0 || hours > 12);
如果你有if語句,沒有理由檢查兩次。改變它一段時間(真),當你得到一個好的輸入可能會破壞?我認爲這不值得讚揚。選民可以解釋嗎? – Cruncher
這完美謝謝。 – HungryHenno
@Cruncher當然,這已經是aetheria的主張。我的(顯而易見的)解決方案只是爲了不擾亂最初的代碼。 – mauretto
我會用「無限」,而循環,擺脫它時,小時圖有效。 while(true) { ... }
是慣用的Java。
Scanner scanner = new Scanner(System.in);
int hours;
while (true) {
System.out.print("Enter hours: ");
hours = scanner.nextInt();
if (hours >= 0 && hours <= 12) {
break;
}
System.err.println("Invalid entry (should be 0-12)");
}
+1現在好多了。 – Cruncher
這完美謝謝。 – HungryHenno
這也很好,趕上很可能的異常「InputTypeMismatch」,但它不是問題的一部分... – NeplatnyUdaj
'if(....)System.out.println(「Error」);'? – Maroun
如果用戶輸入的數字不在0到12之間,則循環繼續循環。你確定這是你想要的嗎? –
不應該反轉這個條件:hours <0 ||小時> 12? – periback2