[英]While - try - catch in Java
我需要一个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
}
您可以像这样将try / catch放在parseInt周围:
while (numberCorrect == false){
System.out.println("Choose a number between 0 and 2");
String option = br.readLine();
try {
number = Integer.parseInt(option);
}catch(NumberFormatException z) {
System.out.println("Try with a correct number");
numberCorrect = false;
option = "-1";
}
switch(option) {
case "0":
System.out.println("Program ends");
numberCorrect = true;
break;
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.