无限循环在java中异常

时间:2016-05-20 12:21:50

标签: java while-loop exception-handling

我准备了以下代码:

public static void main(String[] args) {
Scanner inChoice = new Scanner(System.in);

while(true)
        {
            try
            {
                System.out.println("--------------------------------------------------------");
                System.out.println("Make your choice :");
                System.out.println("For integer - CHOOSE 1");
                System.out.println("For floating-point numbers - CHOOSE 2");
                intChoice = inChoice.nextInt();
                break;
            }
            catch (InputMismatchException imex)
            {
                System.out.println("You have made a wrong selection. Try again");
                continue;
            }
        }
}

问题是当我选择其他东西然后是整数(例如'w')。我的目的是给出一个在例外后再次选择的机会。但相反,我的代码会无限地捕获阻塞和循环并给我消息:

"--------------------------------------------------------"
"Make your choice :"
"For integer - CHOOSE 1"
"For floating-point numbers - CHOOSE 2"
"You have made a wrong selection. Try again"


"--------------------------------------------------------"
"Make your choice :"
"For integer - CHOOSE 1"
"For floating-point numbers - CHOOSE 2"
"You have made a wrong selection. Try again"


"--------------------------------------------------------"
"Make your choice :"
"For integer - CHOOSE 1"
"For floating-point numbers - CHOOSE 2"
"You have made a wrong selection. Try again"

结束......

它没有给我机会再次选择。有人可以解释我,我做错了什么? 感谢

1 个答案:

答案 0 :(得分:1)

发生异常时,不会消耗输入。它留在那里。你需要消耗它,否则它将继续抛出异常。

您只需在异常块中添加此行(当然在continue之前):

inChoice.next();