Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired Efficiency! Implement Chooser UI

Vidhya Sagar
Vidhya Sagar
1,568 Points

for (Song song: msongs) ?????? :(((((((((((((

In this it says for loop cannot iterate through Song. Does anyone have a solution for this?

Craig Dennis
Craig Dennis
Treehouse Teacher

Can you show me a snippet of your code?

Vidhya Sagar
Vidhya Sagar
1,568 Points

Sure. I wanted to print each and every song in the songbook by using the toString overrided method in the song class, so i included an additional condition in the switch , and added a function called show for it . But i get an error saying for loop cannot iterate through.Here is my code.Other files work fine and there is no error in the toString method to . In this code i get an error at the show method. Please check and tell me what i am doing wrong

import java.io.*;
import java.util.*;
public class machine{
    Console console=System.console();
    public  songbook mSongbook;
    public  BufferedReader reader;
    public Map<String, String> mmap;
    public machine(songbook temp){
        mSongbook=temp;
        reader=new BufferedReader(new InputStreamReader(System.in));
        mmap=new HashMap<String,String>();    
        mmap.put("Add","Add a song to the list");
        mmap.put("Exit","Exit form the Application");

    }
private String getaction() throws IOException{
    System.out.printf("There are %d songs available\n",mSongbook.getsize());
    for (Map.Entry<String,String> temp: mmap.entrySet() ){
        System.out.printf("%s --> %s ",temp.getKey(),temp.getValue());
    }
    System.out.println("\n What would you like to do? ");
    String choice=reader.readLine();
    return choice.trim().toLowerCase();
}
public void run(){
    try{
    String choice=" ";

    while (choice !="quit"){
        choice=getaction();
        choice=choice.intern();

            switch (choice) {
                case "add":
                song addsong1=addingsong();
                mSongbook.addsong(addsong1);
                System.out.printf("%s added \n ",addsong1);

                    break;
                case "exit":
                    System.exit(0);
                    break;
                case "show":
                show(mSongbook);
                break;
                default:
                System.out.println("Please Enter only valid options");
                    break;
            }

        }
        } catch (IOException ioe) {
            System.out.println("Problem saving ");
            ioe.printStackTrace();

        }
    }
    //Error here .for each cannot iterate through.
     public static void show (songbook mSongbook1){
         for (song temp5: mSongbook1){
             System.out.printf("%s",temp5);
         }
     }

    public song addingsong() throws IOException{
        System.out.println("What is the name of the Song? ");
        String temp1=reader.readLine();
        System.out.println("What is the name of the artist? ");
        String temp2=reader.readLine();
        System.out.println("What is the link ? ");
        String temp3=reader.readLine();
        return new song(temp1, temp2,temp3);

    }
 private int promptindex(List<String> options ) throws IOException{
     int counter=0;
     for (String option : options){
         System.out.printf("%d-->%s \n",++counter,option);
     }
     System.out.println("What is the option you want to select ");
     String temp4=reader.readLine();
     int answer=Integer.parseInt(temp4.trim());
     return answer-1;

 }

}

3 Answers

Anders Björkland
Anders Björkland
7,481 Points

Hi Edard,

So If I understand you correctly, you are asking about what is called the enhanced for-loop, and how we don't lose any data when we have the same variable being used in each loop?

First off, for(Song song : mSongs) would be similar to this:

for (int i = 0; i < mSongs.size(); i++) {
  Song song = mSongs.get(i);
}

So we are not doing anything with it right now, we are just fetching the next Song-object in the List to our local variable song each time we go through the for-loop. It's up to you what you want to do with the object, maybe you want to print out the title of the song? Fine, you can do that in the loop. Once you've done that, you don't bother with that song anymore and move on to the next and print that song's title. You can have the song-variable referencing a new Song for each loop and print them out. You are not losing any data, you still have the Song-objects in your list.

Was this the answer you were looking for?

Anders Björkland
Anders Björkland
7,481 Points

Hey there, you asked this question a couple of weeks ago, so hopefully you have an answer yourself by now. If not, here is my take on it.

In your show method you want to iterate through a list of songs. What you are trying to do is iterate through a SongBook-object. While the SongBook may contain a list of songs, simply trying to iterate through a SongBook object can be confusing for the Java Machine. Imagine if you have multiple lists, which lists is it you want to iterate. If the SongBook has a getSongs method which returns a list of songs, then that is what you want to use, like this:

for (Song song : mSongBook.getSongs()) {
  System.out.println(song);
} 

A couple of other pointers, you should have capitals on classes and references to class-objects. A reference to a Song-object should be typed as this: Song song. And on that subject, if you find it cumbersome to have so many tempN references, think about what scope you are in. You can have mulitple Song-references named song, as long as there are in different methods that don't overlap.

Hope everything is going fine. Good luck!

hey Anders would you please help me with this

e.g. List<Song> mSongs = new ArrayList<>();

for(Song song: msongs)

I know the song is the variable of type Song but how it works, like in the msongs case how it will get all the data from Song. please explain me. Thank You!

Hey there edard!

What do you mean get all data from Song?

Let me see if I can shed some light on this, as fas as I know.

In the enhanced for loop you mention you're declaring a variable "song" of type "Song" for each variable of type "Song" in "mSongs", so what you're actually doing is copying each "song" in "mSongs" to a new variable called "song" to be used inside the loop.

Hope this helps :)