Search code examples
javaexceptionsumjava.util.scannercontrol-flow

Why is java showing me exception when i am taking input from the user?


public static void inputThenPrintSumAndAverage (){
        Scanner scanner = new Scanner(System.in);
        int count =0;
        int sum =0 ;
        long average = 0;
        boolean isAnInt = scanner.hasNextInt();
        while (true) {
            count++;
            int number = scanner.nextInt();
            if (isAnInt) {
                sum+=number;
                average = Math.round((sum/count));
            } else {
                break;
            }
            scanner.nextLine();
        }
        System.out.println("SUM = "+sum+ " AVG = "+average);
        scanner.close();
    }

When I am giving it a string it gives exception and doesn't even execute the "sum and avg" values. How can I change the code to make it work? If I have some wrong conceptual knowledge please help me understand the concept. Thank you.


Solution

    1. You do not need Scanner#hasNextInt for Scanner(System.in). Also, you do not need the check, if (isAnInt). Instead, you should put a try-catch block.
    2. You should not close Scanner(System.in); otherwise, there is no way to open it again without restarting the JVM.

    Both the above thing are required when you use the Scanner for a File.

    Demo:

    import java.util.InputMismatchException;
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            // Test
            inputThenPrintSumAndAverage();
        }
    
        public static void inputThenPrintSumAndAverage() {
            Scanner scanner = new Scanner(System.in);
            int count = 0;
            int sum = 0;
            long average = 0;
            while (true) {
                try {
                    int number = scanner.nextInt();
                    sum += number;
                    count++;
                } catch (InputMismatchException e) {
                    break;
                }
            }
            average = Math.round((sum / count));
            System.out.println("SUM = " + sum + " AVG = " + average);
        }
    }
    

    A sample run:

    2
    3
    5
    8
    abc
    SUM = 18 AVG = 4
    

    Note: you can get a better precision for average if you declare it as double and store the floating-point calculation into it without rounding e.g.

    import java.util.InputMismatchException;
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            // Test
            inputThenPrintSumAndAverage();
        }
    
        public static void inputThenPrintSumAndAverage() {
            Scanner scanner = new Scanner(System.in);
            int count = 0;
            int sum = 0;
            double average = 0;
            while (true) {
                try {
                    int number = scanner.nextInt();
                    sum += number;
                    count++;
                } catch (InputMismatchException e) {
                    break;
                }
            }
            average = (double) sum / count;
            System.out.println("SUM = " + sum + " AVG = " + average);
        }
    }
    

    A sample run after this change:

    2
    3
    5
    8
    abc
    SUM = 18 AVG = 4.5
    

    It will also be useful for you to understand this concept.