gpt4 book ai didi

java - 我的代码有什么问题吗?做 while 并 try catch

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

不断出现语法错误,插入 while 表达式来完成 do 语句。它可能是一些简单的东西,比如大括号等。

{
int num = 0;
//flag
boolean inputOk = false;
Scanner s = new Scanner (System.in);

do {
try {
System.out.println("Enter a number....");
num =s.nextInt();

System.out.println("you entered : " + num);
// got here then things are good
inputOk = true;

} catch (InputMismatchException ex) {
System.out.println("Again please....digits only");
// flush the scanner
s.next();
}

} while (inputOk != true);
s.close();
System.out.println("Thank you");
}

最佳答案

在您的代码中,您缺少 do 的结束大括号“}”。对于扫描仪,最好使用资源尝试。这是工作代码

    int num = 0;
//flag
boolean inputOk = false;
try (Scanner s = new Scanner(System.in)) {
do {

try {
System.out.println("Enter a number....");
num = s.nextInt();

System.out.println("you entered : " + num);
// got here then things are good
inputOk = true;

} catch (InputMismatchException ex) {
System.out.println("Again please....digits only");
// flush the scanner
s.next();

}
}
while (inputOk != true);
}
System.out.println("Thank you");

关于java - 我的代码有什么问题吗?做 while 并 try catch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40606860/

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