S Personal S Personal - 1 month ago 6
Java Question

How to create two dimensional grid with two-d. array?

This is my current code:

public static void main(String[] args) {
int [][] twoD = new int [5][5];

/*for(int i = 0; i<5; i++){
for(int j = 0; j<5; j++){
System.out.print(twoD[i][j] + "");
}
}*/

}
}


I can't seem to do it. I got confused and I removed the part of testing w/commenting. Just ignore that.

I am aiming to get a two dimensional array like this:

1 2 3 4 5

2 4 6 8 10

3 6 9 12 15

4 8 12 16 20

5 10 15 20 25

However, I just don't get it. How can I get that result? I'm a beginner at java.

Answer

First, you need to populate the array with data, and you forgot System.out.println for each row of the array.

int [][] twoD = new int [5][5];

// populate array with data
for(int i = 0; i<5; i++){
    for(int j = 0; j<5; j++){
        twoD[i][j] = (j+1)*(i+1);
    }
}

// print result
for(int i = 0; i<5; i++){
    for(int j = 0; j<5; j++){
        System.out.print(twoD[i][j]);
        System.out.print(" ");
    }            
    System.out.println();
}
Comments