中級 › ArrayIndexOutOfBoundsException の原因と直し方 › パターン1
ArrayIndexOutOfBoundsException の原因と直し方
添字が0始まりであることの帰結です。
1 public class Main { 2 public static void main(String[] args) { 3 int[] nums = {10, 20, 30}; 4 for (int i = 0; i __ nums.length; i++) { ^ 5 System.out.println(nums[i]); 6 } 7 } 8 }
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 3 out of bounds for length 3exited with code 1
空欄を埋めてビルドを通す
長さ3の配列の添字は0,1,2です。全要素を回るループは < が正解です。
次の問題