以随机顺序播放曲目java

时间:2015-10-25 01:12:44

标签: java random arraylist shuffle

我走在正确的轨道上吗?这必须以随机顺序播放arraylist中的每一首曲目。

public void randomAllTrack() { 

    int shuffle = getNumberOfTracks();
    int shuffleplay = randomTrack.nextInt(shuffle);
    Track track = tracks.get(shuffleplay);
    int i=0;

    while(i < getNumberOfTracks())
    {player.startPlaying(track.getFilename());
        System.out.println("Now playing: " + track.getArtist() + " - "
        + track.getTitle());
        i++;}
}

2 个答案:

答案 0 :(得分:1)

假设tracksCollection,您可以在执行for-each loop后使用Collections.shuffle(List),我可以使用格式化的IO。像

这样的东西
public void randomAllTrack() {
    List<Track> randomTracks = new ArrayList<>(tracks);
    Collections.shuffle(randomTracks);
    for (Track track : randomTracks) {
        player.startPlaying(track.getFilename());
        System.out.printf("Now playing: %s - %s%n", track.getArtist(),
                track.getTitle());
    }
}

答案 1 :(得分:0)

如果您只需要初始随机播放,请创建List并使用Collection List<Track> tracks = new ArrayList<>(); Collections.shuffle(tracks); for (Track track : tracks) { System.out.println("Playing track: " track.getFilename()); }