java - 无法让我的整数相加以获得正确的输出
问题描述
所以我正在努力做我的功课,这是一个问题:
编写一个程序,提示用户读取两个整数并显示它们的总和。如果输入的不是整数,您的程序应该捕获抛出的 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));
}
}
解决方案
用这种方法检查:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numArray = new int[2];
int count = 0;
while (count <= 1) {
try {
System.out.print("Enter an integer: ");
int number = input.nextInt();
System.out.println("The number entered is " + number);
numArray[count] = number;
count++;
} catch (InputMismatchException ex) {
System.out.println("Try again. (" + "Incorrect input: an integer is required)");
input.nextLine();
}
}
int num1 = numArray[0];
int num2 = numArray[1];
System.out.println((num1 + num2));
}
推荐阅读
- javascript - 用新值替换 localStorage
- javascript - 为什么我使用 Deferred 的 jQuery 对话框不等待用户选择?
- search - 过滤表上的表搜索?
- android - DialogFlow 在 WebView Android 中不起作用
- angular - 与使用桌面的移动设备相比,Angular 应用程序加载速度较高
- oracle - 如何对每个进行分组并按最大值排序
- javascript - Redux 传奇没有调用 API
- html - 离子新手如何使列表项更大
- freertos - FreeRTos 高频 ISR
- java - 尝试导出数据时发生 Oracle SQL Developer InvocationTargetException