【发布时间】:2015-12-15 21:33:58
【问题描述】:
这里是编程初学者,我在错误/异常处理方面遇到了麻烦,因为我不知道该怎么做。对于我的菜单系统(下面的代码),我希望它在输入 1-6 以外的任何内容时提醒用户,try catch 是最好的方法吗?有人可以告诉我应该如何实施吗?
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循环中将这么多语句链接在一起
-
无效输入不是异常行为。这是正常行为,应该通过某种定期验证来处理。如果值不在允许的范围内或不是整数,则输出一条消息。
-
是的,同意@tnw。我会改变标题。真的很误导人。
-
无效输入完全可能是异常行为。问题是您能否以相同的方法从无效输入中恢复并要求更多输入。在某些输入无效的情况下抛出异常是完全合理的。这个缝看起来不像这样,但是当你得到错误的输入时,不要完全排除例外。
标签: java error-handling exception-handling