为什么我得到这个异常错误?

问题描述:

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对象)。然后我输入“亚当”,成功删除。然后菜单再次重复,我再次选择4以删除“神秘河”。这也取消了成功。重复菜单,我再次选择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 

问题是这样的:

for (int x = 0; x <= DVDlist.size(); x++) { ... } 

你必须将其更改为

for (int x = 0; x < DVDlist.size(); x++) { ... } 

理由是,在列表中的第一个项目是不是在指数1 0,但索引出发从0Lists (like Java arrays) are zero based

如果你的列表中包含了10个项目,最后一个项目是在9位,而不是10。这是为什么你不能使用x <= DVDlist.size()

java.lang.IndexOutOfBoundsException: Index: 4, Size: 4 

这意味着什么,我说。列表中的4个元素,但最后一个元素是在位置即大小 - 1

0,1,2,3 --> COUNT = 4 // it starting from 0 not 1 
+0

哇,这是对我的脸整个时间的前面...... – trama 2013-04-08 17:46:14

+0

@trama所以这是它如何工作的: ) – Sajmon 2013-04-08 17:48:32

+0

非常感谢你! – trama 2013-04-08 17:50:39