简体   繁体   English

如何在java中初始化2D字符串数组

[英]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. 我能理解的是,我可能需要一个for循环。

The quickest way I can think of is to use Arrays.fill(Object[], Object) like so, 我能想到的最快的方法是使用Arrays.fill(Object[], Object)

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 "-". 这是使用For-Each迭代board1String[] (s)并用“ - ”填充它们。 It then uses Arrays.deepToString(Object[]) to print it. 然后使用Arrays.deepToString(Object[])打印它。

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] = "-";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM