扫描仪将不记得先前输入的整数

时间:2015-09-20 21:51:16

标签: java java.util.scanner

我正在尝试编写一个基本计算器,它需要两个数字并添加它们。首先它假设输入的数字是整数,如果不是,它抛出并捕获异常并假定输入的输入是双精度。该程序工作正常,除非第一个输入的数字是整数,第二个是双重的,它只是挂起而什么都不做。

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

0 个答案:

没有答案