我在while循环中做出了选择菜单。为了确保用户有一个有效的选择,我把菜单本身放在一个try catch块中:围绕选择菜单尝试捕捉
我希望用户获得一个新的机会,如果发生异常,所以我把try-catch块放入一段时间(真)的循环。但是,使用这种循环,动作编码的部分变成不可达代码。
有没有办法做得更好?
还有一个问题,我如何防止用户输入不存在的选项?
while (choice != 0) {
/* Ask for player's choice */
while(true) {
try
{
BufferedReader menuInput = new BufferedReader(new InputStreamReader(System.in));
System.out.println();
System.out.println("Please choose between the following options:'");
System.out.println(" (1) Make new animal");
System.out.println(" (2) Feed Animals");
System.out.println(" (3) Count animals");
System.out.println(" (0) Quit");
System.out.print("Enter your choice: ");;
choice = Integer.parseInt(menuInput.readLine());
} catch (NumberFormatException ex) {
System.err.println("Not a valid number");
} catch (IOException e) {
System.out.println("Failed to get input");
}
}
// first choice option:
if (choice == 1) {
//actions
}
// second choice option:
if (choice == 2) {
//actions
}
// third choice option:
if (choice == 3) {
//actions
}
}
System.out.print("Thank you for playing!")
应该有一些条件*断*循环。例如,一个'break'声明。 – David
您可以编写一个额外的私有方法,在处理当前选择之前验证输入。 – pidabrow