I am trying to create a program that allows me to create a grid using a 2D array and nested for loop. The problem is that when I run the program numbers do not form a table, they instead are printed out in a vertical column.
I first setup the array with 3 rows, each having random values. I then use a nested for loop where the first loop is meant to create the rows for which the loop will run and the second loop is meant to create the columns.
package nestedLoops;
public class Trial_1 {
public static void main(String[] args) {
int[][] grid = {
{1, 2, 3, 4, 5},
{1, 2, 3, 4},
{1, 2, 3, 4, 5}
};
for(int i=0; i<grid.length; i ) {
for(int j=0; j<grid[i].length; j ) {
System.out.println(grid[i][j]);
}
}
}
}
However when I run the above code I get this output:
1
2
3
4
5
1
2
3
4
1
2
3
4
5
I am very new to coding and have just started arrays, I would greatly appreciate any assistance or guidance that you guys can give me thanks.
CodePudding user response:
I think you need something like that:
for (int[] ints : grid) {
for (int anInt : ints) {
System.out.print(anInt);
}
System.out.println();
}
In the second loop you need to print 'anInt' and to wrap a line you need to add a line break between the loops.
CodePudding user response:
You have to advance the output to the new line after printing each row.
For that, you need to a System.out.println();
statement after the nested loop.
In the nested loop you need to use System.out.print();
(not println
) for printing the numbers of every row. And you also need to add a delimiter (white space, tabulation, etc.) between the numbers inside the row, or else they will get jumbled like that 12345
.
int[][] grid = {{1, 2, 3}, {11, 22, 33}};
for (int i = 0; i < grid.length; i ) {
for (int j = 0; j < grid[i].length; j ) {
System.out.print(grid[i][j] "\t");
}
System.out.println();
}
Output
1 2 3
11 22 33