簡體   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