編程初學者在這裏,我有錯誤/異常處理的麻煩,因爲我沒有線索如何做。對於我的菜單系統(下面的代碼),我想讓用戶在輸入1-6以外的任何內容時提醒用戶,嘗試抓住最好的方法嗎?有人可以告訴我應該如何實施?Java異常和錯誤處理
do
if (choice == 1) {
System.out.println("You have chosen to add a book\n");
addBook();
}
///load add options
else if (choice == 2) {
System.out.println("Books available are:\n");
DisplayAvailableBooks(); //call method
}
////load array of available books
else if (choice == 3) {
System.out.println("Books currently out on loan are:\n");
DisplayLoanedBooks(); //call method
}
//display array of borrowed books
else if (choice == 4) {
System.out.println("You have chosen to borrow a book\n");
borrowBook(); //call method
}
//enter details of book to borrow plus student details
else if (choice == 5) {
System.out.println("What book are you returning?\n");
returnBook(); //call method
}
//ask for title of book being returned
else if (choice == 6) {
System.out.println("You have chosen to write details to file\n");
saveToFile(); //call method
}
while (choice != 1 && choice != 2 && choice != 3 && choice != 4 && choice != 5 && choice != 6) ;
menu();
keyboard.nextLine();//catches the return character for the next time round the loop
}
呃不要在while循環中鏈接如此多的語句 – redFIVE
無效的輸入是*不*特殊行爲。這是正常行爲,應該通過常規驗證來處理。如果該值不在允許的範圍內,或者不是整數,則只輸出一條消息。 – tnw
是的,同意@tnw。我會改變標題。真是誤導人。 – gonzo