gpt4 book ai didi

java - java中异常时无限循环

转载 作者:行者123 更新时间:2023-12-01 09:54:34 25 4
gpt4 key购买 nike

我准备了以下代码:

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”)。我的目的是给异常(exception)之后重新选择的机会。但相反,我的代码会无限循环并捕获 block 并给我消息:

"--------------------------------------------------------"
"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"

结束等等...

它不给我重新选择的机会。有人可以解释一下我做错了什么吗?谢谢

最佳答案

当异常发生时,输入不会被消耗。它留在那里。你需要消耗它,否则它会一直抛出异常。

您只需在异常 block 中添加这一行(当然在继续之前):

inChoice.next();

关于java - java中异常时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37346629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com