-1

このようなコード ブロックで入力バッファから「ガベージ」を空にすることをお勧めするのはなぜですか? そうしないとどうなりますか?

try{
    age = scanner.nextInt();
    // If the exception is thrown, the following line will be skipped over.
    // The flow of execution goes directly to the catch statement (Hence, Exception is caught)
    finish = true;
} catch(InputMismatchException e) {
    System.out.println("Invalid input. age must be a number.");
    // The following line empties the "garbage" left in the input buffer
    scanner.next();
}
4

1 に答える 1

2

ループでスキャナーから読み取っていると仮定すると、無効なトークンをスキップしないと、永遠に読み取り続けることになります。つまりscanner.next()、スキャナーを次のトークンに移動します。以下の簡単な例を参照してください。

見つかった整数: 123
無効な入力。年齢は数字でなければなりません。
スキップ: abc
見つかった int: 456

行がないと、String s = scanner.next()「無効な入力」が出力され続けます (最後の 2 行をコメントアウトして試すことができます)。


public static void main(String[] args) {
    Scanner scanner = new Scanner("123 abc 456");
    while (scanner.hasNext()) {
        try {
            int age = scanner.nextInt();
            System.out.println("Found int: " + age);
        } catch (InputMismatchException e) {
            System.out.println("Invalid input. age must be a number.");
            String s = scanner.next();
            System.out.println("Skipping: " + s);
        }
    }
}
于 2012-07-24T16:53:04.907 に答える