簡體   English   中英

為什么我得到“ArrayIndexOutOfBoundsException”?

[英]Why did I get an “ArrayIndexOutOfBoundsException”?

我很擅長編程和上課。 現在,我不是要求任何人為我編寫代碼,但我遇到了運行時錯誤。 在賦值中我們需要讀取一個文件,使用第一行“15”來初始化數組的大小,然后用每行的信息填充數組。

編輯:我不想發布所有的代碼,因為我覺得它看起來太長了但是由於模糊的暗示,這就是它。

文件:

15
produce,3554,broccoli,5.99,1
produce,3554,broccoli,5.99,1
produce,3555,carrots,2.23,0.25
produce,3555,carrots,2.23,0.25
produce,3555,carrots,2.23,0.25
cleaning,2345,windex,5.99,1 unit
cleaning,2345,windex,5.99,1 unit
cleaning,2345,windex,5.99,1 unit
cleaning,2345,windex,5.99,1 unit
cleaning,2346,toilet paper,12.99,4 rolls
cleaning,2346,toilet paper,12.99,4 rolls
cleaning,2335,windex,2.25,1 mini sprayer
cleaning,1342,wipes,3.99,10 units
cleaning,1342,wipes,3.99,10 units
produce,3546,lettuce,2.99,0.5

我的錯誤:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15
    at Inventory.readFile(Inventory.java:45)
    at Inventory.<init>(Inventory.java:12)
    at Supermarket.main(Supermarket.java:3)

有問題的第45行的類(第45行被評論,向右滾動)“

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Inventory{
    Product[] list;
    String[] invData;
    private int i = 0;
    public int count;

    public Inventory (String f){
        readFile(f);
    }

    public int indexOfProduct(int code){        
        for(i=0; i<list.length; i++){ 
            if (list[i] != null)
                if (list[i].getCode() == code)
                    return i;

        }
        return -1;
    }


    public Product delete(int pos){
        Product temp = new Product();
        temp = list[pos];
        list[pos] = null;
        return temp;
    }

    public void readFile(String fileName){
        try{
            File invList = new File (fileName);
            Scanner s = new Scanner(invList);
            int itemCount = s.nextInt();
            list = new Product[itemCount];
            count = itemCount;
            while (s.hasNext()){
                String line = s.nextLine();
                invData = line.split(",");
                if (invData[0].equals("produce")){
                    list[i] = new Produce(invData[1], invData[2], invData[3], invData[4]); // This is Line 45, Where the error occurs
                } else if(invData[0].equals("cleaning")){
                    list[i] = new Cleaning(invData[1], invData[2], invData[3], invData[4]);
                }
                i++;
            }//end of while loop
        } catch (FileNotFoundException Abra) {
            String error = Abra.getMessage();
            System.out.println(error);
            } 
    } // end of method

    public Product findCode(int c){
        for(int i=0; i<list.length;i++)
            if(list[1].getCode() == c)
                return list[i];
        return null;
    }//end of method
}//end of class

為什么我得到“ArrayIndexOutOfBoundsException”? 我希望有人可以指出我邏輯中的缺陷,所以我不再重復了。

您的問題顯然是使用i ,因為這是該行上唯一的變量索引,超出范圍的索引是“15”,這剛剛超過15項數組的末尾。 那么,幾個問題,都圍繞着i的使用:

正如nhellwig所提到的,確保在調用此函數之前i實際上已初始化為0。

此外,您非常相信文件中項目編號的一致性和實際的項目數。 如果i >= itemCount ,您應該產生警告並停止嘗試將項目存儲在數組中,或者使用像ArrayList這樣的容器,它可以增長以容納新項目而不是固定大小的數組。

編輯:另外,我要指出,你增加i不管你讀的項目或沒有,這意味着即使空行會增加i ,在你的列表或陣列超支造成的差距。 由於itemCount是項目的數字,因此您應該堅持使用,只有在讀取實際項目時才增加i

在同樣的精神中,你應該在調用split()之后驗證invData.length == 5 ,因為文件中錯誤的逗號等也可能最終出現OOB錯誤。 當然,對於您的項目,可以對以“生產”或“清理”開頭的行中的元素數量進行假設,但一般來說,對來自用戶創建的文件的數據保持謹慎是很重要的。

我發現答案是我需要一個“s.nextLine();”

因為我使用了“s.nextInt();” 指針只是掛在我文件中“15”的末尾。 然后,當While循環中的第一行“String line = s.nextLine();”時 執行指針從15的末尾移動到列表文件的第2行中的p in產生之前。

工作方法如下所示:

public void readFile(String fileName){
    try{
        File invList = new File (fileName);
        Scanner s = new Scanner(invList);
        int itemCount = s.nextInt();
        s.nextLine(); // This is the new line that made it work
        list = new Product[itemCount];
        count = itemCount;
        while (s.hasNext()){
            String line = s.nextLine(); //moves file pointer over one
            invData = line.split(",");
            if (invData[0].equals("produce")){
                list[i] = new Produce(invData[1], invData[2], invData[3], invData[4]);
            } else if(invData[0].equals("cleaning")){
                list[i] = new Cleaning(invData[1], invData[2], invData[3], invData[4]);
            }
            i++;
        }//end of while loop
    } catch (FileNotFoundException Abra) {
        String error = Abra.getMessage();
        System.out.println(error);
        } 
} // end of method

你多少次調用readFile? 你應該有i = 0; 在功能的開頭。

“i”不應該是全局值,而應該是方法局部變量,初始化為零。

暫無
暫無

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

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