【问题标题】:Java exception and error handlingJava 异常和错误处理
【发布时间】: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


【解决方案1】:

试试 switch 语句

switch() {
    case 1:
        addBook();
        break;
    // etc ...
    default:
        System.out.println("Not a valid choice");
        break;
}

该开关也可以与字符串一起使用,因此您可以将 q 添加到菜单以退出或添加 b 以返回以创建多级菜单。 p>

这可能是需要的,因为来自 readline 的所有用户输入都被视为 字符串,因此除非您将输入转换为 int,否则需要将其包装在 try catch 中,这样会更好默认选项将处理任何意外的用户输入。

case "1": & case "q":

【讨论】:

  • 谢谢,我改成switch语句了!好多了!感谢您的帮助。
【解决方案2】:

一个更“干净”和更容易理解的写法应该是这样的

if(choice < 1 || choice > 6) {
    //invalid input handling
}

while (choice >= 1 && choice <=6) {
    // choice handling and program execution
}

您可以尝试的另一个选项是使用 switch 语句,您可以在这里学习 http://www.tutorialspoint.com/javaexamples/method_enum.htm

而其他 cmets 是正确的,这不是异常处理,而是不受欢迎的输入处理。异常处理将是例如输入空值并抛出空异常错误。即使抛出错误,您也可以使用 try catch 继续运行您的程序。

【讨论】:

  • 感谢您的建议
猜你喜欢
  • 2020-01-04
  • 2014-04-06
  • 2012-09-15
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
  • 2010-11-16
  • 2016-05-17
相关资源
最近更新 更多