gpt4 book ai didi

java - 在java中获取从 'try'到 'catch'的输入

转载 作者:行者123 更新时间:2023-12-01 17:52:34 25 4
gpt4 key购买 nike

这是练习:

If the input is a valid grade number, the program should print "OK". Otherwise, the program should print the entered value and "is not a valid grade." and prompt a grade number again. The program should keep asking grade numbers until the user enters a valid grade number.

输出示例:

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): 2
OK

我在 while 循环中使用带有 NumberFormatException 的“try and catch”。但是,我无法像示例中的第二个那样打印输出。我的输出如下:

Enter grade (0-5): 9
9 is not a valid grade

Enter grade (0-5): two
9 is not a valid grade

Enter grade (0-5): 2
OK

新输入“two”未保存。我该如何解决这个问题?

下面是我的代码:

public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter grade (0-5): ");
int grade = Integer.parseInt(input.nextLine());


if (0 <= grade && grade <= 5) {
System.out.print("OK");
} else {
while (grade < 0 || grade > 5) {
try {
System.out.println(grade + " is not a valid grade.");
System.out.print("\n");
System.out.print("Enter grade (0-5): ");
grade = Integer.parseInt(input.nextLine());
} catch (NumberFormatException nfe) {
System.out.println( " is not a valid grade.");
System.out.print("\n");
System.out.print("Enter grade (0-5): ");
grade = Integer.parseInt(input.nextLine());
}
}
System.out.print("OK");
}

}

最佳答案

如果grade的值为9并且输入为“two”,这一行会发生什么?:

grade = Integer.parseInt(input.nextLine());

该行当然会抛出异常。但更重要的是,这一行不会将字符串值“two”分配给整数变量grade.

将输入存储在字符串中。像这样的东西:

String gradeInput = input.nextLine();
int grade = Integer.parseInt(gradeInput);

如果此操作抛出异常,则输入无效。如果它没有抛出异常,但 grade 超出了要求范围,则输入无效。但这两种情况都需要单独测试。

此外,请注意,您的第一个输入解析位于 try/catch 之外。所以它可能会完全失败。考虑这样的结构:

Scanner input = new Scanner(System.in);
String gradeInput;
int grade = -1;

while (grade < 0 || grade > 5) {
try {
System.out.print("Enter grade (0-5): ");
gradeInput = input.nextLine();
grade = Integer.parseInt(gradeInput);
if (grade < 0 || grade > 5) {
System.out.println(gradeInput + " is not a valid grade.");
System.out.print("\n");
}
} catch (NumberFormatException nfe) {
System.out.println(gradeInput + " is not a valid grade.");
System.out.print("\n");
}
}

我想您可以通过多种方式将其组合在一起并进行重构,以尝试减少此处重复的几行。但重点是,您不想像当前代码那样重复接受输入并将其解析为整数的行。因为如果异常完全在 catch 中或在 try/catch 之外抛出,那么系统将失败。尝试从字符串中解析整数值需要位于try block 中。

关于java - 在java中获取从 'try'到 'catch'的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48382648/

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