2015-12-15 123 views
1

编程初学者在这里,我有错误/异常处理的麻烦,因为我没有线索如何做。对于我的菜单系统(下面的代码),我想让用户在输入1-6以外的任何内容时提醒用户,尝试抓住最好的方法吗?有人可以告诉我应该如何实施?Java异常和错误处理

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 
      } 
+1

呃不要在while循环中链接如此多的语句 – redFIVE

+3

无效的输入是*不*特殊行为。这是正常行为,应该通过常规验证来处理。如果该值不在允许的范围内,或者不是整数,则只输出一条消息。 – tnw

+0

是的,同意@tnw。我会改变标题。真是误导人。 – gonzo

回答

0

尝试switch语句

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

交换机也将与字符串的工作,所以你可以添加一个q到菜单退出或b回去做多级菜单。

这可能是什么需要从readline的所有用户输入被认为是所以,除非你正在转换的输入为int,这将需要包装在一个尝试捕捉,这是因为默认情况下,更好的选择将照顾任何意外的用户输入。

case "1": & case "q":

+0

谢谢,我改成了switch语句!好多了!谢谢您的帮助。 – 88cmurphy

0

一个更“干净”和更易于理解的方式来写它会是这样的

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

而其他评论是正确的,这不是异常处理,而不是在处理。异常处理例如将输入一个空值并抛出一个空的异常错误。在那里你可以使用try catch来继续运行你的程序,即使有错误发生。

+0

感谢您的建议 – 88cmurphy