2014-12-02 93 views
0

在下面的代碼中,即使在我給出輸入之前,我仍然在第80行得到了InputMismatchException。爲什麼是這樣?如何處理這個InputMismatchException?

try { 
    loop:while(true) 
    { 
     choice=sc.nextInt(); 
     switch (choice) { 
      case 1: 
       term=3; 
       break loop; 
      case 2: 
       term=6; 
       break loop; 
      default: 
       System.out.println("Invalid Input.. Enter again"); 
       choice=sc.nextInt(); 
     } 
    } 
} 
catch (InputMismatchException e2) { 
    System.out.println("Wrong Format!! Enter a number"); 
    choice=sc.nextInt(); //line 80 
} 

回答

1

消耗行的末尾:

catch (InputMismatchException e2) { 
    System.out.println("Wrong Format!! Enter a number"); 
    sc.nextLine(); // add this 
    choice=sc.nextInt(); //line 80 
} 

此外,你可能不應該有兩個choice=sc.nextInt();在循環。

而你想把try-catch放入循環中,以便在異常被捕獲後留在循環中。