Не могу получить мои целые числа, чтобы добавить, чтобы получить правильный вывод - PullRequest
0 голосов
/ 04 февраля 2020

поэтому я пытаюсь сделать домашнее задание, вот в чем вопрос:

Напишите программу, которая предлагает пользователю прочитать два целых числа и отображает их сумму. Если в качестве входных данных передается что-либо кроме целого числа, ваша программа должна перехватить возникшее исключение 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));
   }
}

Ответы [ 5 ]

1 голос
/ 04 февраля 2020

Проверьте с этим подходом:

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));
}
1 голос
/ 04 февраля 2020

попробуйте добавить еще одно условие к вашему while и поместить числа в массив.

int[] numbers = new int[2];

и измените это в вашем while l oop:

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

} 

Надеюсь, что это помогло ,

0 голосов
/ 04 февраля 2020

Вы можете добавить два числа внутри блока try

import java .util.InputMismatchException; import java .util.Scanner;

publi c class TestInputMismatch {

publi c stati c 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));

}}

0 голосов
/ 04 февраля 2020

Вам нужно захватить исключение, в этом случае вы можете использовать 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]*"))
0 голосов
/ 04 февраля 2020

Вам нужно сшить логи c. Поскольку вы берете 2 числа, 2 флага гарантируют, что вы получили правильный ввод для обеих переменных. Также оба флага гарантируют, что вы правильно вводите данные для num1 или num2, когда возникает исключение. Если вам нужно ввести n произвольных целых чисел, вы можете использовать динамические коллекции c и добавлять числа в коллекцию.

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