简体   繁体   English

打印多维数组Java

[英]Printing multidimensional array Java

I just wanna print my empty array by for loops. 我只想通过for循环打印我的空数组。

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

What is wrong? 怎么了?

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

You should be using the loop indices to access the array elements, not the array dimensions: 您应该使用循环索引访问数组元素,而不是数组维度:

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

Your solution will cause java.lang.ArrayIndexOutOfBoundsException: 5 you have also a typo balance instead you mean balancee : 您的解决方案将导致java.lang.ArrayIndexOutOfBoundsException: 5您也有错字balance而您的意思是balancee

So Instead you have to use balancee.length and balancee[i].length and not balance[NYEARS][NRATES] , so you have to use balancee[i][j] like this : 因此,您必须使用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();
    }
}

I would prefer generally foreach when I don't need making arithmetic operations with their indices 当我不需要对它们的索引进行算术运算时,我通常更喜欢foreach

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

More importantly, I hope you get why you cannot use balance[NYEARS][NRATES] . 更重要的是,希望您能balance[NYEARS][NRATES]为什么不能使用balance[NYEARS][NRATES]

Just use the built-in Arrays.deepToString() 只需使用内置的Arrays.deepToString()

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

Output 产量

[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