簡體   English   中英

為什么我會收到此異常錯誤?

[英]Why do I get this Exception error?

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以刪除“神秘河”。 這也成功地刪除了。 菜單再次重復,我再次選擇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. 索引從0開始 列表(如Java數組)基於零

如果您的列表有10個項目,則最后一個項目位於第9位而不是10.這就是您無法使用x <= DVDlist.size()

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

這意味着我所說的。 您的列表有4個元素,但最后一個元素位於位置3,即大小 - 1

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM