vendredi 4 mai 2018

java - try/catch holds for + if + switch statements, break; needed after if statement enclosed in for loop that contains switch, why?

I'm kind of new to Java and I can't really understand break; that's needed after if statement in my code. If I don't add the last "break;" statement after "switch" is closed, I get multiple copies of songs that have same title just different time length. However, if I add "break;" I only get one copy of specified song inside user's music file. I'm trying to understand why is that happening. Is it because if I don't break away from "if" statement that holds the "switch" then the switch repeats it self ? Thank you for your help.

try{
     Scanner input = new Scanner(inFile);
        //looping through user requested file of music
        while (input.hasNextLine()){

            //reads new line in the file
            String line = input.nextLine();
            String[] tokens = line.split("[,]");

            // loops through list of all songs
            for (int i = 0; i < allSongs.length; i++){

                String nameOfSong = tokens[1];

                if (allSongs[i].getTitle().equals(nameOfSong)){

                    String playlistTypeName = tokens[0];

                    switch (playlistTypeName){
                        case "playlist1":
                            playlist1.enqueue(allSongs[i]);
                            break;

                        case "playlist2":
                            playlist2.enqueue(allSongs[i]);
                            break;

                        case "playlist3":
                            playlist3.enqueue(allSongs[i]);
                            break;

                        default:
                            break;
                    }
                    break;
                }
            }
        }

Aucun commentaire:

Enregistrer un commentaire