1

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();
       }

3 Answers 3

2

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   ?   ?   ?   ?   ? 
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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();
}

1 Comment

you really don't need a 2d array to print a pattern like this. but you can do it like this if you want to :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.