繁体   English   中英

在Java中打印2D数组元素

[英]Printing out 2d array elements in java

我正在尝试打印2d数组中的元素,但似乎无法格式化它。 每当我尝试格式化它时,都会收到错误消息

    String [][] plants = new String[2][2];
    plants[0][0] = "Rose";
    plants[0][1] = "Red";
    plants[1][0] = "Snowdrop";
    plants[1][1] = "White";

    //String plant;
    //String color;
    for (int i = 0; i<2; i++){
    for (int j = 0; j<2; j++){

        //plant = Arrays.toString(plants[i]);
        //color = Arrays.deepToString(plants[j]);
        //System.out.println(plant + " " + color);
        System.out.println(plants[i][j]);

    }
    }

到目前为止,我已经在一行上打印出了每个元素,但是我希望它像这样打印出来:

玫瑰红

雪花莲白

我已经尝试了注释掉的方法,但是它们也不起作用。

有什么建议么? 谢谢

在内部循环中,执行System.out.print(plants[i][j] + " ");

在外循环中执行System.out.println();

您的for循环应如下所示:

for(int i = 0; i < plants.length; i++)
{
    for(int j = 0; j < plants[i].length; j++)
    {
        System.out.print(plants[i][j]);
        if(j < plants[i].length - 1) System.out.print(" ");
    }
    System.out.println();
}
for (int i = 0; i<2; i++){
    for (int j = 0; j<2; j++){

        System.out.print(plants[i][j]);

    }
     System.out.println();
}

但是,最好使用每种方法来遍历数组。

for (int i = 0; i<2; i++){
    System.out.println(plants[i][0] + " " + plants[i][1]);
}

尝试这个:

 for (int i = 0; i<2; i++){  

        System.out.println(plants[i][0] + " " + plants[i][1]);

    }

您只需要一个循环:

for (int i = 0; i<2; i++)
{
    System.out.println(plants[i][0] + ' ' + plants[i][1]);
}

主要问题是与System.out.println(plants[i][j]);
打印字符串“ Rose”后,它将自动转到下一行。
您可以在内部块中使用简单的print ,而不是println ,这将使光标保持在同一行,而不是转到下一行...

for(int i=0;i<2;i++)
{
    for(int j=0;j<2;j++)
    { 
        System.out.print(plants[i][j]);    
    }  
    System.out.println();  
}
for (int i = 0; i<2; i++) {
    System.out.println(plants[i][0] + " " + plants[i][1]);
}

在内部循环中,您应该使用

System.out.print(plants [i] [j]);

在外循环中,您应该使用System.out.println();。

暂无
暂无

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

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