Java-如何使用For循环(多维)字符串数组

时间:2017-02-27 19:25:24

标签: java arrays multidimensional-array

我能够使用int多维数组进行循环,但是我无法用多数组重现它。

public class array {

public static void main(String[] args) {
    String[][] words = new String[2][3];
    words[0][0] = "a";
    words[0][1] = "b";
    words[0][2] = "c";
    words[1][0] = "d";
    words[1][1] = "e";
    words[1][2] = "f";
   }
}

会喜欢如何迭代

的帮助

作为参考,这就是我为int做的事情

int[][] multi = {
        {3, 4, 5},
        {2, 3, 5, 6, 7},
        {112, 3}
    };
    for (int row = 0; row < multi.length; row++) {
        for (int col = 0; col < multi[row].length; col++) {
            System.out.print(multi[row][col] + " ");

3 个答案:

答案 0 :(得分:1)

你几乎就在那里,适应for循环,不要忘记每一行都是一个阵列......

    String[][] words = new String[2][3];
    words[0][0] = "a";
    words[0][1] = "b";
    words[0][2] = "c";
    words[1][0] = "d";
    words[1][1] = "e";
    words[1][2] = "f";
    for (int row = 0; row < words.length; row++) {
        for (int col = 0; col < words[row].length; col++) {
            System.out.println(words[row][col]);
        }
    }

答案 1 :(得分:1)

使用Java 8,您可以执行以下迭代并打印2d:

Stream.of(words).map(Arrays::toString).forEach(System.out::println);

Output:
a
b
c
d
e
f 

使用Arrays.toString()

打印为一维数组
Stream.of(words).map(Arrays::toString).forEach(System.out::println);

Output:

[a, b, c]
[d, e, f]

答案 2 :(得分:0)

  

如何使用For循环(多维)字符串数组?

String[][] words = new String[2][3];
    words[0][0] = "a";
    words[0][1] = "b";
    words[0][2] = "c";
    words[1][0] = "d";`
    words[1][1] = "e";
    words[1][2] = "f";

为每个循环使用嵌套

完成此类任务的一种方法是对每个循环使用嵌套,但是说已经有其他解决方案来完成相同的任务。

for(String[] word : words)){
 for(String currentWord : word)System.out.println(currentWord); // this is just explanatory, which you can change with what ever you wish to accomplish with this loop.
}

另一种方式:

使用嵌套for循环

for(int i = 0 ;i < 2; i++) {
 for(int j = 0 ;j < 3; j++) {
    System.out.println(words[i][j]); // this is just explanatory, which you can change with what ever you wish to accomplish with this loop.
 }
}