中級 › ArithmeticException: / by zero の原因と直し方 › パターン5
ArithmeticException: / by zero の原因と直し方
int型同士の割り算・剰余算で分母が0だと例外になります。
1 public class Main { 2 public static void main(String[] args) { 3 int[] scores = _________; ^ 4 int sum = 0; 5 for (int s : scores) sum += s; 6 System.out.println(sum / scores.length); 7 } 8 }
Exception in thread "main" java.lang.ArithmeticException: / by zeroexited with code 1
空欄を埋めてビルドを通す
配列が空だとlengthが0になり、平均を求める割り算がそのまま0除算になります。
次の問題