2016-12-26 84 views
0

我在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!") 
+2

应该有一些条件*断*循环。例如,一个'break'声明。 – David

+0

您可以编写一个额外的私有方法,在处理当前选择之前验证输入。 – pidabrow

回答

2

做的非常简单的方法是设置你的循环上方的布尔标志:

boolean waitingForAnswer = true; 

,然后就改变你的while循环条件while(waitingForAnswer)并设置waitingForAnswerfalse一个已经经过公认。

然后,你可以使用相同的结构,以防止他们进入5,或其他任何。简单地标记上到底有没有来检查,如果该值是一个公认的一个,如果它不是一个if,不改变waitingForAnswer

编辑: 顺便说一句,你在底部的if语句串是不是非常高效。如果用户输入“1”,那么if (choice==1)块将触发,然后它将继续检查它是否等于2,如果等于3等,当我们知道它不会。那里使用else if

另一个编辑: 此外,创建您的输入流阅读器以外的循环。目前,您每次循环运行时都会创建一个新的。