【问题标题】:Printing 2D arrays in a toString() using nested for-each loops使用嵌套的 for-each 循环在 toString() 中打印二维数组
【发布时间】:2016-02-08 23:51:45
【问题描述】:

所以我使用 Java 编写了一个二维数组,将歌曲的名称存储在每个插槽中。我必须使用 toString() 方法和嵌套的 for-each 循环来打印这些歌曲。我不知道如何做到这一点。帮忙?

public class Jukebox
{
    public Jukebox()
        {
            String[][] songList = new String[2][3];
            for ( String[] row : songList)
                {
                    for ( String column : row)
                        {
                            songList[0][0] = new String( "Hello" );
                            songList[0][1] = new String( "On My Mind" );
                            songList[0][2] = new String( "Hotel Ceiling" );
                            songList[0][3] = new String( "I Wish" );
                            songList[1][0] = new String( "No Air" );
                            songList[1][1] = new String( "Monsters" );
                            songList[1][2] = new String( "Not Afraid" );
                            songList[1][3] = new String( "Wake Up" );
                            songList[2][0] = new String( "Model" );
                            songList[2][1] = new String( "Thank You" );
                            songList[2][2] = new String( "Apologize" );
                            songList[2][3] = new String( "Fireflies" );
                        }
                }
        }

    public String toString()
        {
             for ( String[] row1 : songList)
                {
                    for ( String column1 : row)
                        {
                           System.out.print(  column1 + " " );
                        }
                    System.out.println( "\n" );
                }
        }
}

【问题讨论】:

    标签: arrays multidimensional-array foreach tostring


    【解决方案1】:

    只需执行以下操作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多