java - try catch 选择菜单

标签 java while-loop menu try-catch

我在 while 循环中制作了一个选择菜单。为了确保用户输入有效的选择,我将菜单本身放在 try catch block 中:

我希望用户在捕获异常时获得新的机会,因此我将 try-catch block 放入 while(true) 循环中。然而,使用这种循环,编码 Action 的部分就变成了无法访问的代码。

有没有办法做得更好?

还有一个额外的问题,如何防止用户输入不存在的选择选项?

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!")

最佳答案

最简单的方法是在循环上方设置一个 boolean 标志:

boolean waitingForAnswer = true;

然后只需将 while 循环条件更改为 while(waitingForAnswer) 并将 waitingForAnswer 设置为 false一份已被接受。

然后您可以使用相同的结构来防止他们输入 5 或其他内容。只需在末尾标记一个 if 即可检查该值是否为可接受的值,如果不是,请勿更改 waitingForAnswer

编辑: 顺便说一句,底部的 if 语句字符串并不是非常有效。如果用户输入“1”,则 if (choice==1) block 将触发,然后当我们知道 a 时,它将继续检查它是否等于 2、是否等于 3 等。事实上它不会。在那里使用else if

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

关于java - try catch 选择菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41336530/

相关文章:

menu - 如何在一个 Menu::widget 中添加多个 Yii2 submenuTemplate?

java - 使用优先级队列的 Dijkstra 算法

java - 在后台加载图像、视频

javascript - 加载功能导致网站停滞

php - PHP 和 MySQL 中的实时搜索(不适用于数组?)

android - ActionBar 共享项目产生 "Android System"thingy

java - JasperReports : Unsupported major. 次要版本 51.0

java - 用于迭代/取消引用混合对象类型列表的 instanceof 和 if-else 语句的替代方案

python - while循环不会在python中停止

android - 如何设置溢出菜单的背景颜色