0

I am trying to program a basic calculator which takes two numbers and adds them. First it assumes the entered numbers are integer if not, it throws and catches an exception and assumes the entered input is double. The program works fine unless the first entered number is integer and the second is double it just hangs and does nothing.

        /* Reads two numbers. Assuming the entered input is integer, Adds
         * the numbers and prints out the result If not integer, throws an
         * InputMismatchException.*/

        Scanner inputSource = new Scanner(System.in);

        try 
        {
            Integer input1, input2, result;

            input1 = inputSource.nextInt();
            input2 = inputSource.nextInt();

            result = input1 + input2;

            System.out.println("The Sum of " + input1 + " and " + input2 + " is " + result);
        }

        catch (java.util.InputMismatchException e) 
        {

            double input1, input2, result;

            input1 = inputSource.nextDouble();
            input2 = inputSource.nextDouble();

            result = input1 + input2;


            System.out.println("The Sum of " + input1 + " and " + input2 + " is " + result);
        }
Farooq Khan
  • 305
  • 1
  • 3
  • 10

1 Answers1

-1

If i am interpreting your problem correctly when you enter a double as the second number it is entering the catch block of your statement and thus you need to enter a second number. To fix this you need to separate your nextInt() method calls to check for doubles instead of having them in the same try catch block, then you should use logic to decide which two values to add together.

Beryllium
  • 556
  • 1
  • 7
  • 20