0

在下面的代码中InputMismatchException,甚至在我给出输入之前,我就已经到达了第 80 行。为什么是这样?

try {
    loop:while(true)
    {
        choice=sc.nextInt();
        switch (choice) {
            case 1: 
                term=3;
                break loop;
            case 2:
                term=6;
                break loop;
            default:
                System.out.println("Invalid Input.. Enter again");
                choice=sc.nextInt();
        }
    } 
}
catch (InputMismatchException e2) {
    System.out.println("Wrong Format!! Enter a number");
    choice=sc.nextInt();  //line 80
}
4

1 回答 1

1

消费行尾:

catch (InputMismatchException e2) {
    System.out.println("Wrong Format!! Enter a number");
    sc.nextLine(); // add this
    choice=sc.nextInt();  //line 80
}

此外,您choice=sc.nextInt();的循环中可能不应该有两个。

并且您想将 try-catch 放在循环中,以便在捕获异常后留在循环中。

于 2014-12-02T07:52:07.120 回答