americanheartbreak americanheartbreak - 1 month ago 8
Java Question

JAVA class array

I am trying to write to code to list all the objects in the class. (Which is working) but I want to get the code to check if there are objects if the player is empty and print out a message to screen if it is. But I cant get it to work. Can anyone assist me please ?

Class

public void listAll()
{
for (Song a : songs) {
if(songs.isEmpty()) //cant get this to check if there are songs on the player.
{
System.out.print("There are no songs on the playlist");
}
else{
System.out.print(a);
}
}
}


Tester

keyIn.nextLine(); //clear the buffer of the previous option
System.out.print("On player are");
player.listAll();
break;

Answer

You need to check the condition if(songs.isEmpty()) outside the for loop because if the list is empty, the execution does not go inside the for loop, so your if condition statement will not get executed at all.

public void listAll() 
    {
         //Check this first
         if(songs.isEmpty())
         {
           System.out.print("There are no songs on the playlist");
           return;//It is even more better to return from here itself
         }

        //NOW, use for loop
        //if songs size is zero, execution does not go inside the for loop
        for (Song a : songs) {
             System.out.print(a);
        }
    }

It is even better, if you can use the return statement to go back to the caller (immediately) from the method (like above), which will indicate that there is no need to process the subsequent lines of code in the method.