0

do while ループがあります。x が 2 つの値の間にあることを確認します。今は int 値を取り込んでいるはずですが、ユーザーが double im を入力すると例外が発生します。ユーザーが double を入力すると、「x は 10 から 150 の間の int でなければなりません:」のように出力されるように、同じ if ステートメントにチェックを組み込むにはどうすればよいですか?

            do {
            x = sc.nextInt();
            if ( x < 10 || x > 150 ) {
                System.out.print("x between 10 and 150: ");
            } else {
                break;
            }
4

3 に答える 3

4

追加のチェックは必要ありません。例外はちょうどそこにあるので、プログラムでそれに応じて行動できます。結局のところ、入力がどれほど正確に間違っていたかは問題ではありません。例外 (NumberFormatException だと思いますか?) をキャッチし、それをキャッチすると、エラー メッセージを出力します。

while (true) try {
    // here goes your code that pretends only valid inputs can occur
    break;   // or better yet, put this in a method and return
} catch (NumberFormatException nfex) {  // or whatever is appropriate
    System.err.println("You're supposed to enter integral values.");
    // will repeat due to while above
}
于 2013-11-06T15:38:46.170 に答える