【问题标题】:ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 for arrays.main [duplicate]ArrayIndexOutOfBoundsException:arrays.main 的索引 3 超出长度 3 [重复]
【发布时间】:2021-11-19 11:14:10
【问题描述】:
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

然后出现错误

【问题讨论】:

    标签: java arrays matrix jdmk


    【解决方案1】:

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

    应该如下?

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

    【讨论】:

    • 哦,谢谢...愚蠢的错误
    【解决方案2】:

    最后我解决了,看看第二个 for 循环,你放了一个 i 而不是 j (在条件中)。如果您使用更重要的变量名称(例如行和列),则更容易发现此类错误

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

    【讨论】:

      猜你喜欢
      • 2019-10-30
      • 2021-04-09
      • 1970-01-01
      • 2020-12-05
      • 2021-05-29
      • 1970-01-01
      • 2021-02-03
      • 2016-02-14
      • 1970-01-01
      相关资源
      最近更新 更多