这是我第一次,请多多包涵。 我正在为一个学校项目创建一个java流媒体服务应用程序,您可以在其中从给定的目录创建不同电影和系列的播放列表。我为菜单创建了一个用于创建播放列表的方法,但我不断收到“Indexoutofbounds”错误。
这是创建播放列表的菜单方法:
void createPlayListMenu() {
System.out.println();
System.out.println("CREATE PLAYLIST -----------------");
System.out.print("Name of your playlist: ");
String name = In.nextLine();
int playListID = this.videoPlayer.createNewPlayList(name);
PlayList p = this.videoPlayer.getPlayList(playListID);
while (true) {
System.out.println("What would you like to do?");
System.out.println(" 1. Add a movie");
System.out.println(" 2. Add a Series");
System.out.println(" 3. Save the playlist");
System.out.println();
int choice = In.nextInt();
if (choice == 1) {
PlayList movies = this.videoPlayer.listMovies();
this.videoPlayer.displayPlayList(movies);
int movieChoice = In.nextInt();
if (movieChoice >= 0 && movieChoice < movies.trackIndexes.size()) {
p.addMovieOrSeries(movies.trackIndexes.get(movieChoice));
System.out.println("Added " + this.videoPlayer.getTrack(movies.trackIndexes.get(movieChoice))
+ " to playlist");
} else {
System.out.println("Invalid movie choice");
}
} else if (choice == 2) {
PlayList series = this.videoPlayer.listSeries();
this.videoPlayer.displayPlayList(series);
int seriesChoice = In.nextInt();
if (seriesChoice >= 0 && seriesChoice < series.trackIndexes.size()) {
p.addMovieOrSeries(series.trackIndexes.get(seriesChoice));
System.out.println("Added " + this.videoPlayer.getTrack(series.trackIndexes.get(seriesChoice))
+ " to playlist");
} else {
System.out.println("Invalid series choice");
}
} else if (choice == 3) {
System.out.println("Added " + p.name + " to playlist");
break;
} else {
System.out.println("Pick an option 1, 2, or 3");
}
}
}
每当我尝试运行代码时,都会收到此错误:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 1
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
at java.base/java.util.Objects.checkIndex(Objects.java:361)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
at VideoPlayer.getPlayList(App.java:466)
at App.createPlayListMenu(App.java:133)
at App.userPlayListsMenu(App.java:112)
at App.runMainMenu(App.java:35)
at App.main(App.java:14)
如果您需要更多详细信息或其余代码,我可以提供。
索引越界异常意味着您正在尝试访问超出数组范围的索引。在我看来,您对 createNewPlaylist 的调用返回 2 作为 id,但视频播放器内部的 ArrayList 的长度只有 1。
该错误可能存在于您的 VideoPlayer 类中。当您调用 createNewPlayList 时,ArrayList 现在会适当增长,或者返回的索引不正确。由于您在此代码片段中只调用了一次 createNewPlaylist,我猜问题是后者 - 在这种情况下索引可能应该是 0 而不是 2。