java 如何在java中初始化一个二维字符串数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26351251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:46:21  来源:igfitidea点击:

How to initialize a 2D array of strings in java

javaarraysstringmultidimensional-arrayinitialization

提问by Senpai

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 循环。

回答by Elliott Frisch

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-Eachto iterate the String[](s) of board1and fill them with a "-". It then uses Arrays.deepToString(Object[])to print it.

这是使用 aFor-Each来迭代String[](s)board1并用“-”填充它们。然后它Arrays.deepToString(Object[])用于打印它。

回答by MadProgrammer

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