首页 > 解决方案 > ArrayIndexOutOfBoundsException:对于arrays.main,索引 3 超出长度 3 的范围

问题描述

import java.util.Scanner;

public class arrays {
    public static void main(String[] args) {
        int i;
        int [][] m1 = new int[2][3];
        int j;

        Scanner sc = new Scanner(System.in);
        
        System.out.println(m1.length);
        System.out.println(m1[0].length);

        for(i = 0; i < m1.length; i++){
            for(j = 0; i < m1[0].length; j++) {
                m1[i][j] = sc.nextInt();
            }
        }
        sc.close();
    }
}

我无法理解为什么会发生此错误。m1.length 和 m1[0].length 打印正确的行和列长度。我给出了以下输入:

1
2
3
4

然后发生错误

标签: javaarraysmatrixjdmk

解决方案


你在内部循环中有一个错字,你超出了第一轴第二个轴,因为i < m[0].length是真的。

应该如下?

  for(j = 0; j < m1[i].length; j++) {

推荐阅读