虽然下面的说明似乎很清楚,但我对如何实现此代码完全感到困惑 .
当代音乐软件最受欢迎的功能之一是能够随机化播放列表中歌曲的顺序 - 一种称为“随机播放”歌曲的动作 . 使用以下伪代码作为指南创建一个shuffle方法:
create a new empty arraylist (called newList)
while (there are still songs left)
randomly select the index of one song on the playlist
remove it from the current playlist and place it at the end of newList
songs = newList
提示:使用Java库中的Random类生成随机数 . 它的方法是:public int nextInt(int n) . 这将返回一个伪随机,均匀分布的int值,该值低至0且高至n . 因此,nextInt(songs.size())为您提供随机索引 . 请记住,每次将随机选择的歌曲添加到newList时,歌曲的大小会减1 . 每次生成随机数时,您都需要考虑到这一点 .
这就是我所导致程序崩溃的原因 . 我需要帮助从数组中检索一首歌,将其删除,并将其放入一个新的数组列表中 . 请帮我!
public int nextInt(int n) {
int index = randomGenerator.nextInt(songs.size());
return index;
}
public void shuffle (){
newList = new ArrayList<Mp3> ();
while (songs.size()>0){
Mp3 song = songs.get(nextInt(songs.size()));
newList.add(song);
System.out.println("new list" + newList);
}
}
4 回答
该程序崩溃,这是因为,在
shuffle
方法中, while (songs.size()>0){ 始终为true
. The size of list is not changed.如果你想用自己的方法编写
shuffle
方法,那么一个简单的方法是 iterater the songs list 和 swap 2 songs of current index i and the song with a random index .最简单的方法是使用 Collections # shuffle 方法使列表随机 .
Collections中相应的shuffle源代码如下:
你在那里正确的轨道,但你忘了实施描述的一个步骤:
需要将Shuffle方法重写为以下内容:
这将随机播放而无需创建新的播放列表(ArrayList) .
基本上这个代码只获取一个播放列表ArrayList,然后在同一个ArrayList中随机播放 .
采用洗牌方法来洗牌 . 希望能帮助到你