Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 946
Senpai Avatar asked Dec 12 '22 03:12

Senpai


2 Answers

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.

like image 118
Elliott Frisch Avatar answered Dec 13 '22 17:12

Elliott Frisch


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] = "-";
    }
}
like image 35
MadProgrammer Avatar answered Dec 13 '22 16:12

MadProgrammer