Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at assg3_Tram.DVDCollection.remove(DVDCollection.java:60)
at assg3_Tram.DVDApplication.main(DVDApplication.java:95)
我通过在我的开关/机箱中选择选项 4(从列表中删除 DVD 对象)来启动我的程序。我输入“Adam”,成功删除。然后菜单再次重复,我再次选择 4 以删除“Mystic River”。这也成功删除。菜单再次重复,我再次选择 4。这次我输入“Mystic Rivers”(带有一个“s”,以测试该 DVD 不在列表中),然后弹出该错误。我已经包含了相关代码和我正在阅读的 .txt 列表。
我正在使用 .txt 文件中的信息填充 ArrayList。每个 DVD 对象有 5 条信息。每一块都是一个单独的线。
public DVD remove(String removeTitle) {
for (int x = 0; x <= DVDlist.size(); x++) {
if (DVDlist.get(x).GetTitle().equalsIgnoreCase(removeTitle)) { // This is line 60.
DVD tempDVD = DVDlist.get(x);
DVDlist.remove(x);
System.out.println("The selected DVD was removed from the collection.");
wasModified = true;
return tempDVD;
}
}
System.out.println("DVD does not exist in the current collection\n");
wasModified = false;
return null;
}
在我的主要课程中:
case 4: {
System.out.print("Enter a DVD title you want to remove: ");
kbd.nextLine();
String titleToRemove = kbd.nextLine();
DVD dvdToRemove = dc.remove(titleToRemove); // This is line 95
if (dvdToRemove != null)
System.out.println(dvdToRemove);
System.out.print("\n");
break;
}
读入带有列表的 .txt 文件。
Adam
Documentary
78 minutes
2012
7.99
Choo Choo
Documentary
60 minutes
2006
11.99
Good Morning America
Documentary
80 minutes
2010
9.99
Life is Beautiful
Drama
125 minutes
1999
15.99
Morning Bird
Comic
150 minutes
2008
17.99
Mystic River
Mystery
130 minutes
2002
24.99