Reputation: 13
I am creating a 5x5 battleship game board. I used a nested for loop to print the board but it's not printing correctly into a 5x5 board. Can you see where I went wrong in my "for loop"? The instructions are to
This is the output:
0000 0000 0000 0000 0000
0000 0000 0000 0000 0000
0000 0000 0000 0000 0000
0000 0000 0000 0000 0000
0000 0000 0000 0000 0000
This is the code I have so far.
public class Location {
int row;
int col;
// constructor, gettes & setters
public static void main(String[] args) {
//creates array
char[][] grid = new char [5][5];
//prints array
for (int row=0; row<grid.length; row++) {
for (int col=0; col<grid[row].length; col++)
System.out.print(grid[row][col]);
System.out.println();
}
}
}
}
Upvotes: 1
Views: 1537
Reputation: 186
Like @Pshemo said in the comments, you need to initialize your grid.
// creates array
char[][] grid = new char [5][5];
// initialize array
for(int row = 0; row < grid.length; ++row) {
for(int col = 0; col < grid[row].length; ++col)
grid[row][col] = 'O';
}
Upvotes: 1