gpt4 book ai didi

java - Java中的while-try-catch

转载 作者:行者123 更新时间:2023-12-02 04:57:19 26 4
gpt4 key购买 nike

我需要一个java程序,询问0到2之间的数字。如果用户写0,程序结束。如果用户写1,则执行一个函数。如果用户写2,它会执行另一个函数。我还想处理错误“java.lang.NumberFormatException”,并显示一条消息,在这种情况下,再次询问用户输入一个数字,直到他写入 0 到 2 之间的数字

我用

public static void main(String[] args) throws IOException {
int number = 0;
boolean numberCorrect = false;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));



while (numberCorrect == false){
System.out.println("Choose a number between 0 and 2");
String option = br.readLine();
number = Integer.parseInt(option);

try {
switch(option) {
case "0":
System.out.println("Program ends");
numberCorrect = true;
break;
case "1":
System.out.println("You choose "+option);
functionA();
numberCorrect = true;
break;
case "2":
System.out.println("You choose "+option);
functionB();
numberCorrect = true;
break;
default:
System.out.println("Incorrect option");
System.out.println("Try with a correct number");
numberCorrect = false;
}
}catch(NumberFormatException z) {
System.out.println("Try with a correct number");
numberCorrect = false;
}
}
}

但是使用此代码,catch(NumberFormatException z) 不起作用,并且程序不会再次要求输入数字。

最佳答案

你永远不会在这里真正捕获NumberFormatException。您的代码基本上执行以下操作:

while (...) {
// this can throw NumberFormatException
Integer.parseInt(...)

try {
// the code in here cannot
} catch (NumberFormatException e) {
// therefore this is never reached
}
}

您想要在这里做的是:

while (!numberCorrect) {
line = br.readLine();
try {
number = Integer.parseInt(line);
} catch (NumberFormatException ignored) {
continue;
}

// etc
}

关于java - Java中的while-try-catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28647822/

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