Java try-catch构造缺少预期输出的部分
问题:创建一个名为ValidateHird的程序,该程序输入用户的分数(0-5)。如果输入是有效的等级编号,程序应打印“OK”。否则,程序应打印输入值和“不是有效等级”。并再次提示等级编号。在用户输入有效的分数之前,程序应不断询问分数 我的代码:Java try-catch构造缺少预期输出的部分,java,try-catch,Java,Try Catch,问题:创建一个名为ValidateHird的程序,该程序输入用户的分数(0-5)。如果输入是有效的等级编号,程序应打印“OK”。否则,程序应打印输入值和“不是有效等级”。并再次提示等级编号。在用户输入有效的分数之前,程序应不断询问分数 我的代码: package chapter1.basic; import java.util.*; public class ValidateThird { public static void main(String[] args) {
package chapter1.basic;
import java.util.*;
public class ValidateThird {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean continueInput = true;
do {
try {
System.out.print("Enter grade (0-5): ");
String input1 = input.nextLine();
int grade = Integer.parseInt(input1);
if (grade > 5) {
System.out.print(input1);
throw new NumberFormatException ();
}
else {
System.out.println("OK");
}
continueInput = false;
}
catch (NumberFormatException ex) {
System.out.println(" is not a valid grade.");
}
} while(continueInput);
}
}
我的输出:
Enter grade (0-5): 9
9 is not a valid grade.
Enter grade (0-5): two
is not a valid grade.
Enter grade (0-5): 4
OK
,我的预期产出:
Enter grade (0-5): 9
9 is not a valid grade.
Enter grade (0-5): two
two is not a valid grade.
Enter grade (0-5): 4
OK
由于变量的作用域,我无法从catch中的try-to-use获取输入。知道如何修复代码以生成预期输出吗
提前谢谢你 您可以将变量移到try范围之外,以便在catch中看到,如下所示:
public static void main(String[] args) throws Exception, IOException {
Scanner scanner = new Scanner(System.in);
String str = "";
boolean continueInput = true;
do {
try {
System.out.print("Enter grade (0-5): ");
str = scanner.nextLine();
int grade = Integer.parseInt(str);
if (grade > 5) {
System.out.print(str);
throw new NumberFormatException();
} else {
System.out.println("OK");
}
continueInput = false;
} catch (NumberFormatException ex) {
System.out.println(str + " is not a valid grade.");
}
} while (continueInput);
scanner.close();
}
在try/catch之外定义那些变量(您想在外部使用的变量),就像input
和continueInput