gpt4 book ai didi

java - 动态添加数组到数组中

转载 作者:行者123 更新时间:2023-12-01 09:17:42 25 4
gpt4 key购买 nike

我正在制作一个 array2,即 array2 = {i,j},并且我有另一个二维数组 e_list={} 。现在我想将 array2 追加到 e_list 中。

     int[][] G = {{0, 0, 0, 1, 1}, 
{0, 0, 1, 1, 1},
{0, 1, 0, 0, 0},
{1, 1, 0, 0, 1},
{1, 1, 0, 1, 0},
};

int[][] e_list = {}; //<-initialize 2D array here

for (int i=0; i < 5; i++){
for (int j=0; j < 5; j++){
if (G[i][j] == 1){
int[] array2 = {i,j};
System.out.print(array2[1]);
System.out.print(",");
System.out.println(array2[0]);
//----------------------------//<-- here I want to add this array2 into that 2D array e_list

//this is one of my failed try;
for (int t=1; t <= 6; t++){
for (int tt=0; tt < 1; tt++){
e_list[t][tt] = array2[tt];
}
}

}
}
}

现在,代码只是打印 array2 的第一个和第二个索引。但我想要这样的东西; e_list = {{3,0}, {4,0}, ... , {1,2}}我想访问 e_list,例如 e_list[0][0] = 3、e_list[1][0] = 4 等

我已经尝试过内部的 for 循环...但没有成功。它说“java.lang.ArrayIndexOutOfBoundsException: 0”

最佳答案

您需要实际告诉 e_list 它有多大,然后才能为其赋值。类似 int[][] e_list = new int[5][5];而不是int[][] e_list = {};

否则 e_list 将没有大小,因此一旦您尝试在其中写入内容,您就会遇到数组索引越界异常(您的数组没有大小,但您试图访问其中的内容)

有趣的是,你的//<-initialize 2D array here评论已经准确地说明了您还需要做什么:D 但是仅仅写评论而不是实际做某事是不够的。

关于java - 动态添加数组到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40420463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com