【问题标题】:Cant get my integers to add to get correct output无法让我的整数相加以获得正确的输出
【发布时间】: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,则它们已正确初始化
  • 我找不到字符串“请输入整数”的打印位置。

标签: java input mismatch


【解决方案1】:

尝试在您的 while 中添加另一个条件并将数字放入数组中。

int[] numbers = new int[2];

并在您的 while 循环中更改它:

int count = 0;
 while (!isValid && count <2) {
    try {
        System.out.print("Enter an integer: ");
        numbers[count] = input.nextInt();
        count++;
        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();
    }

} 

希望对您有所帮助。

【讨论】:

  • boolean continueInput = false; 是什么?
  • while (!isValid 是如何使用的?
【解决方案2】:

用这种方法检查:

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

【讨论】:

  • 非常感谢!我无法理解我做错了什么!
  • @Inez2454 您还没有将输入分配给 num1 和 num2。这个 isValid 布尔标志是无用的,因为您没有在代码中为其分配任何值。最好调试并检查您的代码有什么问题。
【解决方案3】:

您需要将逻辑拼接在一起。当您使用 2 个数字时,2 个标志将确保您获得两个变量的正确输入。此外,当发生异常时,这两个标志都可确保您正确输入 num1 或 num2。 如果您需要输入 n 个任意整数,那么您可能需要使用动态集合并将数字添加到集合中。

   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);

      int num1 = 0;
      int num2 = 0;
      boolean num1Valid = false;
      boolean num2Valid = false;

      while (num1Valid==false || num2Valid==false) {
         try {
           if(num1Valid == false) {
            System.out.print("Enter an integer for num1: ");
            num1 = input.nextInt();
            System.out.println("The number entered for num1 is " + num1);
            num1Valid = true;
           }

           if(num2Valid == false) {
            System.out.print("Enter an integer for num2: ");
            num2 = input.nextInt();
            System.out.println("The number entered for num2 is " + num2);
            num2Valid = true;
           }
         }
         catch (InputMismatchException ex) {
            System.out.println("Try again. (" + "Incorrect input: an integer is required)");
            input.nextLine();
         }
      }
      input.close()
      System.out.println((num1 + num2));
   }

【讨论】:

  • 也感谢您的帮助。将逻辑拼接在一起是有意义的,我只是不确定如何以正确的方式进行。
【解决方案4】:

你需要捕获异常,在这种情况下你可以使用 e.getMessage()

public class TestInputMismatch {

public static void main(String[] args) {

     Scanner input = new Scanner(System.in);

     int num1=0, number=0;
     boolean isValid = false;

     while (!isValid) {
        try {
            System.out.print("Enter an integer: ");
            number = input.nextInt();
            if(number > 0) {
                System.out.println("The number entered is " + number);
            }

            num1 += number;

            System.out.println("are would you like continue the program? Y or 
             N ");
            String condition = input.next();

            if(condition.equalsIgnoreCase("Y")) {
                isValid = false;
            } else {
                isValid = true;
            }
         }
         catch (InputMismatchException ex) {
            System.out.println(ex.getMessage());
            System.out.println("You cannot type words");
            isValid = true;
         }

     }
     System.out.println("Result = " + num1);
     input.close();
 }
}

在另一种情况下,您是否可以使用表达式语言匹配方法

看到下面的例子:

   if(valor.matches("[0-9]*"))

【讨论】:

    【解决方案5】:

    你可以在 try 块中添加两个数字

    导入 java.util.InputMismatchException; 导入 java.util.Scanner;

    公共类 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: ");
            num1 = input.nextInt();
    
            System.out.print("Enter an integer: ");
            num2 = input.nextInt();
    
            System.out.println("The numbers you  entered are " + num1 + ","+num2);
    
            int sum = num1+num2;
            System.out.println("The sum Of the numbers you entered is: "+ sum);
    
            boolean continueInput = false;
         }
         catch (InputMismatchException ex) {
            System.out.println("Try again. (" + "Incorrect input: an integer is required)");
            input.nextLine();
         }
    
      } 
      System.out.println((num1 + num2));
    

    } }

    【讨论】:

      【解决方案6】:
      import java.util.Scanner;
      import java.util.InputMismatchException;
      public class InputMismatch {
          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();
                      numArray[count] = number;
                      count++;
                  } catch (InputMismatchException e) {
                      System.out.println("Please enter an integer.");
                      input.nextLine();
                  }
              }
              System.out.println(numArray[0] + numArray[1]);
              
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-09
        • 1970-01-01
        • 1970-01-01
        • 2020-12-03
        • 1970-01-01
        相关资源
        最近更新 更多