americanheartbreak
americanheartbreak

Reputation: 41

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;

Upvotes: 2

Views: 80

Answers (3)

Vasu
Vasu

Reputation: 22422

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.

Upvotes: 2

Eran
Eran

Reputation: 393781

If songs is empty, the loop won't be entered. You need to check outside the loop :

public void listAll()  {
    if(songs.isEmpty()) {
        System.out.println("There are no songs on the playlist");
    } else {
        for (Song a : songs) {
            System.out.println(a);
        }
    }
}

Upvotes: 2

ItamarG3
ItamarG3

Reputation: 4122

You are trying to loop through an empty list, so the looped code doesn't happen at all. If you check whether the list is empty outside of the loop, then you get the result you wanted.

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

}

Upvotes: 3

Related Questions