Reeggiie
Reeggiie

Reputation: 822

How to display row and column number in 2d array?

I currently have a 2d array of all '?', that displays like this:

 ? ? ? 
 ? ? ? 
 ? ? ? 

I need to display the rows and columns, but I cannot figure out the correct way to do so. Can someone show me what to add to make it look like this:

  0 1 2 
0 ? ? ? 
1 ? ? ?
2 ? ? ?

Below is the code I currently have to display just the '?'s

 // initialize the contents of board
       for ( int i = 0; i < board.length; i++){
           for (int j = 0; j < board[i].length; j++){
               board[i][j] = '?';
           }
       }

 //Print board
       for(int i = 0; i<board.length;i++)
       {
           for(int j = 0; j<board[0].length;j++)
           {
               System.out.print(board[i][j] +"  ");
           }
           System.out.println();
       }

Upvotes: 1

Views: 5357

Answers (3)

Jeeshu Mittal
Jeeshu Mittal

Reputation: 445

Try this:

System.out.print("  ");
for(int i = 0; i < board[0].length; i++){
  System.out.print(i + " ");
}
System.out.println();

for(int i = 0; i < board.length; i++){
  System.out.print(i + " ");
  for(int j = 0; j < board[i].length; j++){
    System.out.print("? ");
  }
  System.out.println();
}

Upvotes: 0

afzalex
afzalex

Reputation: 8652

Have a look at the following code :

//Print board

System.out.printf("%-4s", "");
for (int i = 0; i < board[0].length; i++) {
    System.out.printf("%-4d", i);
}
System.out.println();
for (int i = 0; i < board.length; i++) {
    System.out.printf("%-4d", i);
    for (int j = 0; j < board[0].length; j++) {
        System.out.printf("%-4c", board[i][j]);
    }
    System.out.println();
}

Output :

    0   1   2   3   4   
0   ?   ?   ?   ?   ?   
1   ?   ?   ?   ?   ?   
2   ?   ?   ?   ?   ?   
3   ?   ?   ?   ?   ?   
4   ?   ?   ?   ?   ? 

Upvotes: 2

Justin Kiang
Justin Kiang

Reputation: 1290

Before your //Print board loop, have one loop that prints the column header. Just iterate it board.lengh+1 times, with the first time printing a blank

Between your two for loops, print your row number, that's just i

Upvotes: 0

Related Questions