2017-03-02 8 views
0

私は現在、Ackerman関数の問題を抱えています。私たちはユーザー入力に対してフェールセーフでコードを作成する必要があります。したがって、通常はプログラムをクラッシュさせるユーザー入力があれば、メッセージを送信するだけです。私は、整数値が大きすぎる場合の例外を把握することができましたが、ユーザー入力が整数かどうかをチェックする方法を見つけることができません。私は "InputMismatchException"でブロックをキャッチしようとしましたが、コードが混乱してバグが始まるか、まったく機能しません。Ackermansの機能キャッチの問題を試してください

public static void main(String[] args) { 

//creates a scanner variable to hold the users answer 
Scanner answer = new Scanner(System.in); 


//asks the user for m value and assigns it to variable m 
System.out.println("What number is m?"); 
int m = answer.nextInt(); 




//asks the user for n value and assigns it to variable n 
System.out.println("What number is n?"); 
int n = answer.nextInt(); 


try{ 
//creates an object of the acker method 
AckerFunction ackerObject = new AckerFunction(); 
//calls the method 
System.out.println(ackerObject.acker(m, n)); 
}catch(StackOverflowError e){ 
    System.out.println("An error occured, try again!"); 
} 



} 

}

答えて

0

あなたがtryブロック内で

int n = answer.nextInt(); 

を配置する必要があります。 そして、あなたはjava.util.InputMismatchException

をキャッチすることがありますが、これは私の作品:

public static void main(String[] args) { 

    //creates a scanner variable to hold the users answer 
    Scanner answer = new Scanner(System.in); 

    int m; 
    int n; 
    try{ 
     //asks the user for m value and assigns it to variable m 
     System.out.println("What number is m?"); 
     m = answer.nextInt(); 
     //asks the user for n value and assigns it to variable n 
     System.out.println("What number is n?"); 
     n = answer.nextInt(); 
    }catch(InputMismatchException e){ 
     System.out.println("An error occured, try again!"); 
    } 
} 
関連する問題