gpt4 book ai didi

java - 尝试不要在 while(true) 循环中执行多次

转载 作者:行者123 更新时间:2023-12-01 11:13:59 24 4
gpt4 key购买 nike

我正在编写一个程序的简单部分,其中用户给出出生年份。代码如下:

while(true){
try {
year = input.nextInt();
break;
} catch (InputMismatchException mismatchException) {
System.err.println("year of birth can only have numbers");
}
}

所以如果我给出一个有效的 int (年份是 int 类型),一切都会好的。如果我给出一个像“hello”这样的字符串,我期望它做的是在写入错误消息后再次尝试并询问我一个数字。
我对 try - catch 语句的思考方式是否错误?

最佳答案

试试这个(我猜输入是java.util.Scanner):

while(input.hasNext()) {
if (input.hasNextInt()) {
year = input.nextInt();
break;
} else {
System.out.println("year of birth can only have numbers");
input.next();
}
}
input.close();

关于java - 尝试不要在 while(true) 循环中执行多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32051108/

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