2015-12-15 70 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