Jayla Allen
Jayla Allen

Reputation: 13

How to print a 2d char array into a 5x5 game board and initialize it to store "O's" in JAVA

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

Answers (1)

tezkerek
tezkerek

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

Related Questions