我想打印出这个多维数组的元素,但我得到索引超出范围错误.
public class test {
public static void main(String[] args) {
int array1[][]={{1,2,3,4},{5},{6,7}};
for (int i=0; i<3;i++){
for (int j=0; j<4;j++){
System.out.println(array1[i][j]);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,使用这样写的循环,你假设嵌套数组的长度都是4(并且它们不是).你最好这样做:
for (int i=0; i < array1.length;i++) {
for (int j=0; j < array1[i].length;j++) {
...
}
}
Run Code Online (Sandbox Code Playgroud)