繁体   English   中英

打印多维数组Java

[英]Printing multidimensional array Java

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

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();
    }
}

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

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

您的解决方案将导致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();
    }
}

当我不需要对它们的索引进行算术运算时,我通常更喜欢foreach

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

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

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

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

产量

[null, [], [1], [2, 3]]
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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM