2014-04-06 49 views
0

我想創建一個代碼,其中int應該被輸入,然後有例外,如果int不是9和99之間,另一個例外,如果一個雙輸入,而不是int,然後一個如果輸入字符串,則爲第三個異常。我該怎麼做呢?我有以下我迄今爲止,但不知道如何糾正它。感謝int的三個例外

public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 
    boolean correct = true; 
    do { 
     try { 
      System.out.println("Enter an Integer between 9 and 99"); 
      int number = input.nextInt(); 
      if (number >= 9 && number <= 99) { 
       System.out.println("Thank you, Initialization completed"); 
       correct = false; 
      } else if (number < 9 || number > 99) { 
       throw new Exception("Integer is not within the range"); 
      } 
      if (input.hasNextDouble()) { 
       throw new Exception("Integer not entered"); 
      } else { 
       correct = false; 
      } 
      if (input.hasNext("")) { 
       throw new NumberFormatException("Integer not entered"); 
      } else { 
       correct = false; 
      } 
     } // check for range 
     catch (Exception e1) { 
      System.out.println("Number is not within 9 and 99"); 
      System.out.println(); 
      input.nextLine(); 
     } catch (Exception e2) { 
      System.out.println("An integer was not entered"); 
      System.out.println(); 
      input.nextLine(); 
     } catch (NumberFormatException e3) { 
      System.out.println("An integer was not entered"); 
      System.out.println(); 
      input.nextLine(); 
     } 
    } while (correct); 
} 

回答

1

方法.getMessage()返回構造給出的字符串:

throw new Exception("HERE"); 

當你發現異常,你也搭上NumberFormatException的,InputMismatchException時,等 所以你必須趕上更加廣泛的持續。

catch (NumberFormatException e3) { // Precisier goes first 
    System.out.println("An integer was not entered"); 
    System.out.println(); 
    input.nextLine(); 
} 
catch (Exception e1) { 
    System.out.println(e1.getMessage()); 
    System.out.println(); 
    input.nextLine(); 
}