2017-08-04 24 views
0

このコードが期待どおりに動作しないのはなぜですか?Whileループでスキャナを使用

public class FinalTest { 
    public static void main (String [] args) { 

    Scanner in = new Scanner(System.in); 
    int k = 0; 

    boolean askForInput = true; 

    while (askForInput) { 
     System.out.print("Enter an integer: "); 
     try { 
     k = in.nextInt(); 
     askForInput = false; 
     } catch (InputMismatchException e) { 
     System.out.println("ERR: Not an integer!!"); 
     } 
    } 

    } 
} 

nextInt()はintとして入力をスキャンしようとすると、それがint型でない場合、それは例外ERRスローする必要があります:ない整数。何がバグですか、どうして入力を再度促さないのですか? ERRメッセージを画面に表示し続けます。

Aあなたは、私はそれがreduntantない作るために キャッチSystem.out.print("Enter an integer: ");を入れて見ることができます。これは正しいフォームで

+2

エラーメッセージ –

+0

を印刷した後に '' in.nextLine(); ''を追加してみてください!ありがとう! – py9

答えて

0

、あなたは再びループを開始する必要があります。

public static void main(String[] args){ 
      System.out.print("Enter an integer: "); 
      Scanner in = null; 
      int k = 0; 

      boolean askForInput = true; 

      while (askForInput) { 

       in = new Scanner(System.in); 
       try { 
       k = in.nextInt(); 
       askForInput = false; 
       } catch (InputMismatchException e) { 
       System.out.println("ERR: Not an integer!!"); 
       askForInput = true; 
       System.out.print("Enter an integer: "); 

       } 
      } 
      System.out.print("End"); 

      } 
     } 

出力:documentation of nextIntから

enter image description here

0

以下に説明するように、次のトークンが有効なint型の値に変換できない場合、このメソッドはInputMismatchExceptionをスローします。 変換に成功すると、スキャナは一致した入力を通過します。言い換えれば

それが数値として認識されない場合は、nextIntはトークンストリームにトークンを残します。 1つの修正は、catchブロックのトークンを破棄するためにnext()を使用することです。

2

整数でない場合、nextInt()呼び出しは入力(たとえば「abc」)を消費しません。だから、ループの次回には、あなたがすでに入力した "abc"がまだ見えます。それは永遠に続きます。だから、より良いInteger.parseInt(in.nextを())を使用する:あなたはtryブロックを実行すると

public static void main (String [] args) { 

    Scanner in = new Scanner(System.in); 
    int k = 0; 

    boolean askForInput = true; 

    while (askForInput) { 
     System.out.print("Enter an integer: "); 
     try { 
      k = Integer.parseInt(in.next()); 
      askForInput = false; 
     } catch (NumberFormatException e) { 
      System.out.println("ERR: Not an integer!!"); 
     } 
    } 
} 
+0

となります。しかし、なぜそれは "整数を入力"も印刷されていないのですか?それがループの始まりなので、 – py9

+0

@ py9それは私のためにそれを印刷します。コードをダブルチェックし(コンパイル/実行前に保存されている場合)、ここにソリューションを使用していることを確認してください。 – Pshemo

+0

私の悪い。正常に動作します。ありがとう! – py9

0

askForInputは関係なく、最初の繰り返しで毎回あなたのループを終了kの値のfalseに変更なっています。

while (askForInput) { 
     System.out.print("Enter an integer: "); 
     try { 
     k = in.nextInt(); 
     askForInput = false; 
     } catch (InputMismatchException e) { 
     System.out.println("ERR: Not an integer!!"); 
     askForInput = true; //add this line resetting askForInput to true 
     } 
    } 
+0

しかし、それが偽に変わるとループを終了しないでしょうか? – py9

関連する問題