Senpai
Senpai

Reputation: 41

How to initialize a 2D array of strings in java

I know how to declare the array and I have done so:

String[][] board1 = new String[10][10];

Now I want to make it so that every space is "-" by default (without the quotes of course). I have seen other questions like this but the answers didn't make sense to me. All I can understand is that I would probably need a for loop.

Upvotes: 4

Views: 14999

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347314

You could do ...

String[][] board1 = new String[][] {
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
    {"-", "-", "-", "-", "-", "-", "-", "-", "-", "-"},
};

or

String[][] board1 = new String[10][10];
for (int outter = 0; outter < board1.length; outter++) {
    String[] row = new String[board1[outter].length];
    for (int inner = 0; inner < row.length; inner++) {
        row[inner] = "-";
    }
    board1[outter] = row;
}

or

String[][] board1 = new String[10][10];
for (int outter = 0; outter < board1.length; outter++) {
    for (int inner = 0; inner < board1[outter].length; inner++) {
        board1[outter][inner] = "-";
    }
}

Upvotes: 6

Elliott Frisch
Elliott Frisch

Reputation: 201467

The quickest way I can think of is to use Arrays.fill(Object[], Object) like so,

String[][] board1 = new String[10][10];
for (String[] row : board1) {
    Arrays.fill(row, "-");
}
System.out.println(Arrays.deepToString(board1));

This is using a For-Each to iterate the String[](s) of board1 and fill them with a "-". It then uses Arrays.deepToString(Object[]) to print it.

Upvotes: 9

Related Questions