RaymondNoodle
RaymondNoodle

Reputation: 131

How can I print a two-dimensional array of characters in Java, to create a 20x20 grid?

I am trying to print a 2d array of periods in Java, however, I can not get the formatting correctly. I am able to create a similar layout NOT using a 2d array. However, I will need to be working with a 2d array to finish the project. I have tried using Arrays.deepToString(); but did not find it useful.

My goal is to have a 20x20 grid of periods like this: ** Without the S and the X enter image description here

My way without using a 2d array:

for (int i = 20; i >= 1; i--) {
            for(int j = 1; j <= 20; j++) {
                    System.out.print(" .");
            }
            System.out.print("\n");
        }

My try using a 2d array:

final int rows = 20;
final int columns = 20;

for (int i = 0; i < rows; i++) {
     for (int j = 0; j < columns; j++) {
              board[i][j] = ".";
     }
     System.out.println(Arrays.deepToString(board));
}

Upvotes: 1

Views: 394

Answers (2)

Faheem azaz Bhanej
Faheem azaz Bhanej

Reputation: 2396

You have to print your 2D array outside outer loop but you print this 2D array result outside inner loop. After that you have to remove bracket and comma through java replace() method.

Here down is modified code:

import java.util.*;
public class Main
{
    public static void main(String[] args) {
        final int rows = 20;
        final int columns = 20;
        String board[][] = new String[rows][columns];
        
        // OUTER LOOP
        for (int i = 0; i < rows; i++) {
            // INNER LOOP
            for (int j = 0; j < columns; j++) {
                board[i][j] = ".";
            }
        }
        System.out.print(Arrays.deepToString(board).replace("],", "\n")
                                                .replace(",", "")
                                                .replace("[[", " ")
                                                .replace("[", "")
                                                .replace("]]", ""));
    }
}

Upvotes: 1

Idle_Mind
Idle_Mind

Reputation: 39132

Put the two together?...

  public static void main(String[] args) {       
    final int rows = 20;
    final int columns = 20;
    String board[][] = new String[rows][columns];

    for (int row = 0; row < board.length; row++) {
      for (int col = 0; col < board[row].length; col++) {
        board[row][col] = ".";
      }
    }

    display2Darray(board);
  }

  public static void display2Darray(String[][] arr) {
    for (int row = 0; row < arr.length; row++) {
      for (int col = 0; col < arr[row].length; col++) {
        System.out.print(arr[row][col]);
      }
      System.out.println();
    }
  }

Upvotes: 3

Related Questions