编程初学者在这里,我有错误/异常处理的麻烦,因为我没有线索如何做。对于我的菜单系统(下面的代码),我想让用户在输入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