0

I just wanna print my empty array by for loops.

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

5 Answers 5

1

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();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I would prefer generally foreach when I don't need making arithmetic operations with their indices

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].

Comments

1

Your solution will cause java.lang.ArrayIndexOutOfBoundsException: 5 you have also a typo balance instead you mean 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 :

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

3 Comments

balance[NYEARS][NRATES] this will print only the last value, it is wrong. It is out of bound.
More importantly, I wonder who gave +1 even if there was a wrong point.
@snr i think 80% is correct and 10% is wrong so this is why, we are human we make mistakes, we are not angels, i will give you +1 for your comment, you already teaches me something so you deserve +1 :)
0

Just use the built-in Arrays.deepToString()

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

Output

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.