Home > Software design >  How to solve ArithmeticException Error : / by zero
How to solve ArithmeticException Error : / by zero

Time:04-05

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

CodePudding user response:

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

CodePudding user response:

You could also show a different message if the counter is 0.

if(counter != 0) {
    average = Math.round(sum / counter);
    System.out.println("SUM = "   sum   " AVG = "   (double)average);
} else {
    System.out.println("You did not provide any valid value.");
}
scanner.close();
  • Related