繁体   English   中英

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

[英]Java- How to use For Loop with (Multidimensional) Array of Strings

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

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] + " ");

您快要准备好了,适应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]);
        }
    }

使用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]

如何将For Loop与(多维)字符串数组一起使用?

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.
 }
}

暂无
暂无

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

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