1

だから私はこのコードを持っています:

protected void giveNr(Scanner sc) {
    //variable to keep the input
    int input = 0;
    do {
      System.out.println("Please give a number between: " + MIN + " and " + MAX);
      //get the input
      input = sc.nextInt();
    } while(input < MIN || input > MAX);
}

人間が文字や文字列などの整数ではない sth を入力すると、プログラムがクラッシュし、エラーが発生しますInputMismatchException。間違ったタイプの入力が入力されたときに、人間が再度入力を求められるようにするにはどうすれば修正できますか (プログラムはクラッシュしませんか?)

4

1 に答える 1

2

をキャッチしInputMismatchException、何が問題だったかをユーザーに通知するエラーメッセージを出力して、ループをもう一度回ることができます。

int input = 0;
do {
    System.out.println("Please give a number between: " + MIN + " and " + MAX);
    try {
        input = sc.nextInt();
    }
    catch (InputMismatchException e) {
        System.out.println("That was not a number.  Please try again.");
        input = MIN - 1; // guarantee we go around the loop again
    }
while (input < MIN || input > MAX)
于 2012-04-07T23:43:12.030 に答える