2017-03-16 2 views
-3

私は今例外的に大学の授業をしています。私はいくつかのコードを書いたが、うまくいかない場所に誰かが気付くことができるかどうか疑問に思っている。どんな助けでも大歓迎です。大学の授業の例外処理

私はInputMismatchExceptionを扱うために特別にクラスを作成しましたが、整数ではなく配列にdoubleを入力すると、プログラムは例外処理よりもクラッシュします。

ありがとうございました。

public class Lab8 { 
    public static void main(String[] args) { 
     ArrayList<Integer> a = new ArrayList<Integer>(); 
     Scanner s = new Scanner(System.in); 
     boolean x = true; 
     while (x == true) { 
      try { 
       System.out.println("Enter the next integer: "); 
       /*Autoboxing takes place here. The primitive type "int" taken in from the 
       user is converted to an Integer object.*/ 
       Integer i = s.nextInt(); 
       a.add(i); 
      } catch (InputMismatchException e) { 
       System.out.println("You must enter an integer."); 
      } 

      System.out.println("Would you like to enter another integer? (Y/N): "); 
      char y_n = s.next().charAt(0); 
      if (y_n == 'Y') { 
       x = true; 
      } else { 
       x = false; 
      } 
     } 
     for (int i = 0; i < a.size(); i++) { 
      System.out.println(a.get(i)); 
     } 

    } 
} 
+2

を追加してください。アプリケーションがキャプチャしていない別の例外が発生しているように聞こえますが、すべての例外を捕捉するInputMisMatchExceptionではなくExceptionを常に使用できます。 – SPlatten

+2

これをデバッガでステップ実行すると、スローされた例外とは何行ですか? – David

答えて

0

ちょうどこの

System.out.println("Would you like to enter another integer? (Y/N): "); 
s = new Scanner(System.in); 
char y_n = s.next().charAt(0); 
0

よう

s = new Scanner(System.in); 

を追加スキャナは入力からint型を引くことができなかったので、それはまだそこに立ち往生しています。新しいものを探す前に入力をクリアする必要があります。そうでなければnext.charAt(0)がダブルの最初の数字になります(あなたの例では)。 catch節に、

s.next();