2016-04-28 20 views
1

下面的代碼在try catch catch捕獲異常後終止。不允許我從菜單選項中進行選擇。所以我的問題是我必須對此代碼進行哪些更改,以便我可以循環,以便我可以再次獲得用戶輸入。程序在switch語句中使用try catch塊後終止

public class Main { 

     public static void main(String[] args) { 

      Modify modifyObj = new Modify(); 

      int choice = 0 ; 

      Scanner input = new Scanner(System.in); 

      //begin loop 
      do { 
       try{ 

       //display menu 

       System.out.println("Choose one option from following option available: "); 
       System.out.println("0) Exit program. "); 
       System.out.println("1) Create a Roster"); 
       System.out.println("2) Modify a Roster"); 
       System.out.println("3) Delete a Roster"); 



       choice = input.nextInt(); //gets user input 

        switch (choice) { 

         case 1: 
//code 
         break; 


         case 2: 
    //code 
           break; 

         case 3: 
          //code 
          break; 


        }// end of switch statement 
        break; 
       }//end oftry 
       catch(InputMismatchException inputMismatchException){ 
        System.out.println("Enter integer value between 0 and 7:"); 
        continue; 
       } 


      }while (choice!=0); //loop until user exit 0. 

     }//end of main 
    }// end of Main class 
+1

爲什麼有'打破;'了'開關結束後(選擇)'塊?這不會將你踢出循環嗎? – KevinO

+0

這是我的代碼中的錯字,我只是改變仍然有同樣的問題。 – user6238843

+0

它完全停止。 – user6238843

回答

0

確保choice不是0之前continue;

catch(InputMismatchException inputMismatchException){ 
    System.out.println("Enter integer value between 0 and 7:"); 
    choice = 1; // <-- not 0. 
    continue; 
} 

注意默認choice0的初始值。

你可以使用方法

如果你提取你的邏輯到一個(或兩個)實用工具方法來顯示菜單並獲得用戶的選擇它會簡化的事情;像

private static void showMenu() { 
    System.out.println("Choose one option from following option available: "); 
    System.out.println("0) Exit program. "); 
    System.out.println("1) Create a Roster"); 
    System.out.println("2) Modify a Roster"); 
    System.out.println("3) Delete a Roster"); 
} 

private static int getUserOption(Scanner input) { 
    while (true) { 
     showMenu(); 
     if (input.hasNextInt()) { 
      int t = input.nextInt(); 
      switch(t) { 
      case 0: case 1: case 2: case 3: 
       return t; 
      } 
     } else { 
      input.nextLine(); 
     } 
    } 
} 

然後你main可以調用它像

public static void main(String[] args) { 
    Modify modifyObj = new Modify(); 

    Scanner input = new Scanner(System.in); 
    int choice; 
    // begin loop 
    do { 
     choice = getUserOption(input); 
     if (choice != 0) { 
      System.out.printf("You chose %d.%n", choice); 
     } 
    } while (choice != 0); // loop until user enters 0. 
}// end of main 
+0

切換後有一個'break'。這不是原因而不是這個? – Gendarme

+0

@Gendarme也許我很愚蠢地認爲OP關於*以下代碼在try catch catch捕獲異常*之後終止。 –

+0

當我改變選擇爲1我的代碼無限運行。 – user6238843