How to solve ArithmeticException Error : / by zero

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


}

此方法旨在打印出用户输入的数字的总和和平均值。当用户输入非整数类型时,我试图打印“SUM = 0 AVG = 0”,但我遇到了这个错误。 线程“主”中的异常java.lang.ArithmeticException:/零

在尝试除法之前,您应该确保计数器不是 0

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

如果计数器为 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();