Java 2D 数组无法将值写入最后一个值索引

我的 Java 2D 数组有问题。


int y = 5;

int x = 4;

int[][] map = new int[y][x];


for (int j = 0; j <= y ; j++) {

    for (int l = 0; l <=x; l++) {

        System.out.println("j: " + j + " l: " + l);

        map[j][l] = 1;

    }

}

Java 在到达数组中的最后一个值时抛出此异常:


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4

将 for 循环更改为“j < y”和“l < x”有助于解决问题,但第 5 列和第 4 行显然没有被打印出来。

http://img1.mukewang.com/61de93760001586204220137.jpg

有什么办法可以解决这个问题,我错过了什么吗?


喵喔喔
浏览 176回答 3
3回答

阿波罗的战车

因为 Java 中0的数组是索引的,所以数组的长度不是有效的索引。因此,您应该在 for 循环中使用<而不是<=:for (int j = 0; j < y; j++) {&nbsp; &nbsp; for (int l = 0; l < x; l++) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("j: " + j + " l: " + l);&nbsp; &nbsp; &nbsp; &nbsp; map[j][l] = 1;&nbsp; &nbsp; }}

慕妹3242003

从两个循环中删除等于&nbsp; &nbsp; int y = 5;&nbsp; &nbsp; int x = 4;&nbsp; &nbsp; int[][] map = new int[y][x];&nbsp; &nbsp; for (int j = 0; j < y; j++) {&nbsp; &nbsp; &nbsp; &nbsp; for (int l = 0; l < x; l++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("j: " + j + " l: " + l);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map[j][l] = 1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }没有第 5 列,因为它的大小是 5。所以索引像 0、1、2、3、4。第 4 行也是如此。由于该大小为 4,因此索引将变为 0、1、2、3

元芳怎么了

在java中,数组索引是从0到length-1。所以,在你的情况下, from&nbsp;0toy-1 = 4和 from&nbsp;0to&nbsp;x-1 = 3。你的输出似乎完全没问题。的第一个值j应该是 0。 有 5 个不同的值j, 有 4 个不同的值l。改回<=以<在for循环。(这部分导致错误:l不能从0到4,只能从0到3)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java