Hieu Tran February 2016

Printing 2D arrays in a toString() using nested for-each loops

So I wrote a 2D array using Java that stores the names of songs in each of its slots. I have to print these songs using a toString() method and nested for-each loops. I have no idea as to how to do this. Help?

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" );
                }
        }
}

Answers


gmoney12 February 2016

Just do something like:

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

Post Status

Asked in February 2016
Viewed 3,268 times
Voted 4
Answered 1 times

Search




Leave an answer