3 回答
TA贡献1785条经验 获得超4个赞
这会起作用。我希望你能理解解决方案。如果解析失败则 Integer.parseInt()抛出。NumberFormatException
void test() {
while (true) {
int aNumber;
try {
aNumber = Integer.parseInt(br.readLine());
System.out.println("Hurray you enterd a number! It is " + aNumber + ".");
return;
} catch (NumberFormatException | IOException e) {
System.out.println("Error: Something went wrong. Please try again.\n");
}
}
}
TA贡献1779条经验 获得超6个赞
您的代码不起作用,因为输入字符串或除 之外的任何其他类型int都会生成 aNumberFormatException并且您没有捕获它。
if 语句是不必要的,因为只有给出文本时才会执行 catch 块。转换时将引发异常,因此下面的行将不会执行。
请检查此代码
void Test() {
while (true) {
try {
aNumber = Integer.parseInt(br.readLine());
System.out.println("Hurray you enterd a number! It is " + aNumber + ".");
return;
} catch (NumberFormatException | IOException e) {
e.printStackTrace();
System.out.println("Error: Something went wrong. Please try again.\n");
}
}
}
TA贡献1864条经验 获得超2个赞
您可以做的最简单的事情就是捕获NumberFormatException然后打印您想要的消息。
请参阅下面的工作示例:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadNumber {
public static void main(String[] args) {
int aNumber = 0;
while (true) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
aNumber = Integer.parseInt(br.readLine());
} catch (NumberFormatException e) {
System.out.println("That wasn't a number.");
continue;
} catch (IOException e) {
e.printStackTrace();
}
if (aNumber >= 1) {
System.out.println("Hurray you entered a number! It is " + aNumber + ".");
continue;
} else {
System.out.println("Error: Something went wrong. Please try again.\n");
}
}
}
}
添加回答
举报