我刚刚开始了关于异常处理的课程,我不确定我在代码中做错了什么--我的目标是创建一个UI,询问用户他们有多少宠物,并检查输入是否为整数。有人能指出哪里出了问题吗?
我已经尝试对我的消息使用label.setText(),并且我还更改了我使用的异常(我尝试了NumberFormat)。
下面是我使用的代码块(这是我第一次遇到EH,所以我觉得这个话题有点混乱)
String value = input.getText();
int intval = 0;
intval = Integer.parseInt(value);
try {
if (0 >= intval) {
throw new IllegalArgumentException();
}
else
throw new InputMismatchException();
}
catch(IllegalArgumentException e)
{
String outputMessage = "The number must be an integer no less than 0!";
label1.setText(outputMessage);
}
catch(InputMismatchException i) {
System.out.println("Please enter an integer.");
System.out.println("You entered: " + intval);
}
finally
{
System.out.println("You own " + intval + " pets.");
}我想包括的例外情况是,如果用户输入的是另一个数字类型而不是整数,以及如果用户输入的是负整数而不是正整数或0。我的代码可以运行,但是try-catch块并不能真正工作。
发布于 2019-04-17 18:18:29
看起来这段代码有很多缺陷!首先,你不应该将输入作为字符串,如果你将输入作为整数,你可以引发InputMismatchException,通过它你可以很容易地告诉用户“只输入整数值”,通过将输入作为字符串,你将无法做到这一点。不要使用finally块,因为无论你的代码抛出多少异常,finally块都会被执行。即使你最后输入了-1 (在执行代码时),它也会显示"you have -1 pets:“消息,因为不管发生什么,finally块都会被执行!我重构了代码,使其以同样的方式工作。
Scanner input = new Scanner(System.in);
boolean exceptionHit = false;
int value = 0;
try {
value = input.nextInt();
if (value <= 0) {
throw new IllegalArgumentException();
}
}
catch (IllegalArgumentException e) {
String outputMessage = "The number must be an integer no less than 0!";
label1.setText(outputMessage);
exceptionHit = true;
} catch (InputMismatchException i) {
System.out.println("Please enter an integer.");
exceptionHit = true;
}
if (exceptionHit == false)
System.out.println("You have " + value + " pets");我已经删除了最后的区块,所以最后一条消息不会每次都显示!我添加了一个布尔值,而不是它,如果遇到任何异常,布尔值将被设置为true。
https://stackoverflow.com/questions/55724093
复制相似问题