【问题标题】:Why do I get this Exception error?为什么我会收到此异常错误?
【发布时间】:2013-04-08 17:41:00
【问题描述】:
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)

我通过在我的 switch/case 中选择选项 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   

【问题讨论】:

    标签: java exception


    【解决方案1】:

    问题是这样的:

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

    你必须把它改成

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

    原因是 List 中的第一项不是索引 1 而是 0。索引从 0 开始Lists (like Java arrays) are zero based.

    如果您的列表有 10 个项目,则最后一个项目位于位置 9 而不是 10。这就是您不能使用 x &lt;= DVDlist.size() 的原因

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

    这就是我所说的。您的 List 有 4 个元素,但最后一个元素位于 3 位置,即 size - 1

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

    【讨论】:

      猜你喜欢
      • 2013-11-08
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 2018-06-22
      • 2016-01-01
      • 1970-01-01
      相关资源
      最近更新 更多