Search code examples
javajava.util.scannerarithmeticexception

How to solve ArithmeticException Error : / by zero


import java.util.Scanner;

public class InputCalculator {
    public static void main(String[] args) {
        inputThenPrintSumAndAverage();
    }

    public static void inputThenPrintSumAndAverage(){
        Scanner scanner = new Scanner(System.in);

        int sum = 0;
        int counter = 0;
        long average = 0L;
        while(true){
            System.out.println("Enter a number : ");
            boolean isAnInt = scanner.hasNextInt();

            if(!isAnInt){
                break;
            }else{
                counter++;
                int number = scanner.nextInt();
                sum +=number;
            }

            scanner.nextLine();
        }



        average = Math.round(sum / counter);
        System.out.println("SUM = " + sum + " AVG = " + (double)average);
        scanner.close();
    }


}

This method aims to print out the sum and average for the numbers that were entered by the user. I was trying to print "SUM = 0 AVG = 0" when user entered a non-integer type but I encounter this error. Exception in thread "main" java.lang.ArithmeticException: / by zero


Solution

  • You should make sure the counter isn't 0 before attempting the division:

    if(counter != 0) {
        average = Math.round(sum / counter);
    }
    System.out.println("SUM = " + sum + " AVG = " + (double)average);
    scanner.close();