2017-11-07 28 views
0

私はこのコードtry/catchを使用すると無限ループを回避するにはどうすればいいですか?

public void askUserForStrategy(){ 

    try{ 

     System.out.println("What strategy do you want to use?\n"); 
     System.out.println("1 = Math.random\t  2 = System time\t " 
     + "3 = Sum of Math.random and System time"); 

     int strategy = sc.nextInt(); 

     selectStrategy(strategy); 

    } 

    catch(InputMismatchException Exception){ 

     System.out.println("That is not an integer. Try again.\n"); 
     askUserForStrategy(); 

    } 

} 

私はそれがやりたいことは基本的に整数を入力するようユーザーに依頼して、ユーザのユーザタイプ例えば文字列の場合には、その例外をキャッチし、方法を開始しているがありますもう一度(整数値を入力するようユーザーに依頼する)。しかし、このメソッドは、ユーザーがString型を入力するとループします。

+2

ドゥプログラムの流れに 'try-catch'を使わないでください。回復不能な例外のみを処理する必要があります。同じプロセスを再試行しないでください。 – Filburt

答えて

2

nextInt()が例外をスローすると、Scannerオブジェクトは次の呼び出しで同じ文字列を使用しようとします。

try内に新しいScannerオブジェクトを割り当ててみてください。またはcatchnextLine()に電話をかけてください。違法行は破棄されます。

あまりにも多くの違法な入力(非常に多く、理想的には無限の試行を持つことが望ましい)後にスタックオーバーフローが発生するため、この方法は良くありません。

try本文の末尾にdo-whilereturnを使用することをおすすめします。

+0

ありがとう!メソッド内でスキャナオブジェクトを移動したところ、完全に機能しました。 –

1

これを試してみてください:

public void askUserForStrategy() { 

for(int i=0; i<1; ++i) { 
    try{ 

    System.out.println("What strategy do you want to use?\n"); 
    System.out.println("1 = Math.random\t  2 = System time\t " 
    + "3 = Sum of Math.random and System time"); 

    int strategy = sc.nextInt(); 

    selectStrategy(strategy); 
    break; //break loop when there is no error 
    } 

    catch(InputMismatchException Exception){ 

    System.out.println("That is not an integer. Try again.\n"); 
    //askUserForStrategy(); 
    continue; //for clarity 

    } 
} 
} 
1

をたぶん、あなたはこの

public void askUserForStrategy(){ 
Boolean loopFlag = true; 
while(loopFlag) { 
try{ 

    System.out.println("What strategy do you want to use?\n"); 
    System.out.println("1 = Math.random\t  2 = System time\t " 
    + "3 = Sum of Math.random and System time"); 

    int strategy = sc.nextInt(); 
    Integer.parseInt(strategy); 
    loopFlag = false; 
    selectStrategy(strategy); 
} 

catch(Exception e){ 

    //Parse has failed due to wrong input value, But loop will continue 

}}} 
0

ような何かを探している。これは、あなたが探しているかもしれ..

public void askUserForStrategy() { 
     while (true) { 
      try { 
       Scanner sc = new Scanner(System.in); 
       System.out.println("What strategy do you want to use?\n"); 
       System.out.println("1 = Math.random\t  2 = System time\t " + "3 = Sum of Math.random and System time"); 

       int strategy = sc.nextInt(); 
       System.out.println("Selected strategy : " +strategy); 
       break; 
      } catch (Exception e) { 
       System.out.println("That is not an integer. Try again.\n"); 
       continue; 
      } 
     } 
     // selectStrategy(strategy); 
    } 

ユーザーが文字列を選択した場合、もう一度オプションを求めます。

ユーザーが整数を選択した場合、それは、ユーザが選択した戦略オプションを取ると、プログラムの流れを継続しますが...(手段がブレークの助けを借りて、whileループから出た後、selectStrategyメソッドを呼び出す)

おかげ

関連する問題