首页 > 解决方案 > 无法让我的整数相加以获得正确的输出

问题描述

所以我正在努力做我的功课,这是一个问题:

编写一个程序,提示用户读取两个整数并显示它们的总和。如果输入的不是整数,您的程序应该捕获抛出的 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));
   }
}

标签: javainputmismatch

解决方案


用这种方法检查:

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));
}

推荐阅读