【发布时间】:2021-10-27 10:53:36
【问题描述】:
我编写了一些代码来模拟“歌曲”的“播放列表”。 “播放列表”由一个linkedList 表示,它应该能够让用户在列表中顺序地向前或向后移动。我使用 switch 语句来允许用户浏览播放列表。问题在于,如果用户选择移动到下一首歌曲的选项,程序会遍历整个播放列表,然后在打印“您已到达列表末尾”语句时卡住。我的 switch 语句中的 break 语句被忽略。每次用户选择此选项时,如何让linkedList 只迭代一次?
public static void playSongs(LinkedList playList){
boolean quit = false;
int userInput;
boolean forward = true; //track direction of movement through the linkedList
ListIterator<Song> listIterator = playList.listIterator(); //iterate through the linkedList
if(playList.isEmpty()){
System.out.println("No songs in playlist");
return;
}else{
System.out.println("Now Playing " + listIterator.next().getTitle());
printMenu();
}
userInput = scanner.nextInt();
scanner.nextLine();
while(!quit){
switch(userInput){
case 0:
System.out.println("Exiting playlist");
quit = true;
break;
/*problem area: if case 1 is selected, the list iterator should print the title of the next song in the list and then break, instead it ignores the "break" statement and prints the title of every remaining song, then keeps printing "you've reached the end of the list."*/
case 1:
if(!forward){
if (listIterator.hasNext()){
listIterator.next();
}
forward = true;
}
if(listIterator.hasNext()){
System.out.println("Now Playing " + listIterator.next().getTitle());
}else{
System.out.println("Reached end of playlist");
forward = false;
}
break;
case 2:
if(forward) {
if (listIterator.hasPrevious()) {
listIterator.hasPrevious();
}
forward = false;
}
if(listIterator.hasPrevious()){
System.out.println("Now playing: " + listIterator.previous().getTitle());
}else{
System.out.println("Already at beginning of playlist");
forward = true;
}
break;
case 3:
if(forward){
if(listIterator.hasPrevious()){
System.out.println("Now replaying " + listIterator.previous().getTitle());
forward = false;
}else {
System.out.println("Replaying first song");
}
}else{
if(listIterator.hasNext()){
System.out.println("Now replaying " + listIterator.next().getTitle());
forward = true;
}else{
System.out.println("Replaying last song in list");
}
}
}
}
}
【问题讨论】:
标签: java loops iterator switch-statement