1

我有这个代码

package example;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Example {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int rep;
    int[] arraya = new int[2];
    do {
        try {
            rep = 0;
            System.out.print("input col :");
            int kol = input.nextInt();
            System.out.print("input value :");
            int val = input.nextInt();
            arraya[kol] = val;
        } catch (InputMismatchException e) {
            System.out.println("input must integer");
            rep = 1;
            input.next();
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("out of range");
            rep = 1;
        }
    } while (rep == 1);
}
}

为什么我必须添加input.next();catch(InputMismatchException e);避免无限循环?

为什么incatch(ArrayIndexOutOfBoundsException e);不需要input.next();避免无限循环?

catch(ArrayIndexOutOfBoundsException e);,循环运行良好,但input.next();为什么它不同于catch(InputMismatchException e);

4

1 回答 1

1

因为如果您输入一个非整数字符,它不会int kol = input.nextInt();等待用户再次输入,它会继续尝试读取之前输入的字符,因为它没有被消耗。int

如果输入越界int,它将消耗,并在下int一次迭代中读取下一个。

于 2015-01-12T08:10:18.400 回答