【发布时间】:2020-02-04 02:22:05
【问题描述】:
所以我正在努力做我的功课,这就是问题:
编写一个程序,提示用户读取两个整数并显示它们的和。如果输入的不是整数,您的程序应该捕获抛出的 InputMismatchException,并通过打印“请输入一个整数”提示用户输入另一个数字。
下面是示例运行以及我应该测试的内容。
SAMPLE RUN #1: java InputMismatch
Enter an integer: 2.5↵
Please enter an integer↵
Enter an integer: 4.6↵
Please enter an integer↵
Enter an integer: hello!↵
Please enter an integer↵
Enter an integer:7↵
Enter an integer:5.6↵
Please enter an integer↵
Enter an integer:9.4↵
Please enter an integer ↵
Enter an integer:10↵
17↵
当我测试我的代码并输入整数时,它按预期工作,但是,当两个输入都正确输入时,我坚持让整数相加。我做错了什么?
import java.util.InputMismatchException;
import java.util.Scanner;
public class TestInputMismatch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
boolean isValid = false;
while (!isValid) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
boolean continueInput = false;
}
catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
System.out.println((num1 + num2));
}
}
【问题讨论】:
-
在这段代码 sn-p 中,缺少对 num1 和 num2 的赋值。 num1 和 num2 都初始化为 0,之后没有赋值。此外,while 循环有条件!isValid,无法看到 isValid 在哪里更改以终止循环。所以它现在看起来像无限循环。您可能希望显示完整的程序文本。
-
消除样本运行中的一些混淆。我只需要在测试程序时输入这些数字。结果应该是只添加了正确的整数。因此,样本运行结束时的 17。当输入小数时,我的代码将其踢回来并说它不正确,我遇到的问题是让正确的整数加在一起。
-
您可以改用整数对象并将它们初始化为
null- 如果不是null,则它们已正确初始化 -
我找不到字符串“请输入整数”的打印位置。