简体   繁体   English

在Java中打印2D数组元素

[英]Printing out 2d array elements in java

I'm trying to print out elements in a 2d array, but can't seem to format it. 我正在尝试打印2d数组中的元素,但似乎无法格式化它。 Anytime I try to format it I get an error 每当我尝试格式化它时,都会收到错误消息

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

    }
    }

What I have so far prints out each element on an individual line, but I want it to print out like: 到目前为止,我已经在一行上打印出了每个元素,但是我希望它像这样打印出来:

Rose Red 玫瑰红

Snowdrop White 雪花莲白

I've tried the methods commented out, but they won't work right either. 我已经尝试了注释掉的方法,但是它们也不起作用。

Any suggestions? 有什么建议么? Thanks 谢谢

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

In the outer loop do System.out.println(); 在外循环中执行System.out.println();

Your for-loop should look like this: 您的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();
}

However you are better off using for each to iterate over the array. 但是,最好使用每种方法来遍历数组。

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

Try this: 尝试这个:

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

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

    }

You need only one loop: 您只需要一个循环:

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

The main problem is with the System.out.println(plants[i][j]); 主要问题是与System.out.println(plants[i][j]);
After printing a String "Rose" it will automatically go to next Line.... 打印字符串“ Rose”后,它将自动转到下一行。
you can use simple print in inside block instead of println which would keep cursor in same line instead of going to next Line... 您可以在内部块中使用简单的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]);
}

In the inner loop you should use 在内部循环中,您应该使用

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

And in the outer loop you should use System.out.println(); 在外循环中,您应该使用System.out.println();。

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

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