打印多维数组Java

时间:2017-05-14 08:13:29

标签: java arrays

我只想通过打印我的空数组循环。

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

有什么问题?

int NYEARS = 5;
int NRATES = 3;

double[][] balancee = new double[NYEARS][NRATES];
for (int i = 0; i < NYEARS; i++) {
    for (int j = 0; j < NRATES; j++) {
        System.out.print(balance[NYEARS][NRATES] + " ");
        System.out.println();
    }
}

5 个答案:

答案 0 :(得分:1)

您应该使用循环索引来访问数组元素,而不是数组维度:

for (int i = 0; i < NYEARS; i++) {
    for (int j = 0; j < NRATES; j++) {
        System.out.print(balance[i][j] + " ");
        System.out.println();
    }
}

答案 1 :(得分:1)

您的解决方案会导致java.lang.ArrayIndexOutOfBoundsException: 5您输入错误balance而不是balancee

所以相反,你必须使用balancee.lengthbalancee[i].length而不是balance[NYEARS][NRATES],所以你必须像这样使用balancee[i][j]

for (int i = 0; i < balancee.length; i++) {
    for (int j = 0; j < balancee[i].length; j++) {
        System.out.print(balancee[i][j] + " ");
        System.out.println();
    }
}

答案 2 :(得分:1)

当我不需要使用索引进行算术运算时,我更喜欢 foreach

for (double[] x : balancee) { 
    for (double y : x) { 
        System.out.print(y + " ");
 }        
    System.out.println(); 
 }

更重要的是,我希望你明白为什么你不能使用balance[NYEARS][NRATES]

答案 3 :(得分:0)

只需使用内置的Arrays.deepToString()

即可
int[][] foo = { null, {}, { 1 }, { 2, 3 } };
System.out.println(Arrays.deepToString(foo));

输出

[null, [], [1], [2, 3]]

答案 4 :(得分:0)

int NYEARS = 5; //This is the size
int NRATES = 3; //This is the size

double[][] balancee = new double[NYEARS][NRATES]; //<-- balancee vs balance



for (int i = 0; i < NYEARS; i++) {
for (int j = 0; j < NRATES; j++) {
    System.out.print(balance[NYEARS][NRATES] + " "); //<-- use i and j instead of size. 
    System.out.println();
    }
}