2014-03-05 21 views
0

我收到的錯誤是一個數組索引越界異常,但我不知道它爲什麼發生在它的位置。OOP庫存程序

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

public class Inventory 
{ 
    //Maximum amount of objects 
    private static int MAX_ITEMS = 100; 

    //Iteration from item to item 
    private int d_nextItem = 0; 

    //Array for the different objects 
    private Stock[] d_list = new Stock[MAX_ITEMS]; 

    public static void main(String[] args) throws FileNotFoundException 
    { 
     Inventory inventory = new Inventory(); 
     inventory.loadList(args[0]); 
     //Costs printing out,rough draft, toString not made 
     System.out.println("COSTS"); 
     inventory.getTotalCost(); 
     //Total Selling price printing out 
     System.out.println("SELLINGP"); 
     inventory.getTotalSellingPrice(); 
     System.out.println("SAMOUNT"); 
    } 

特定的錯誤是在異常線程「主」 java.lang.ArrayIndexOutOfBoundsException:在Inventory.main(Inventory.java:27)0指向朝向主的inventory.loadList方法。運行程序時只會出現錯誤,我不知道爲什麼會發生。

這是loadList方法,並且迭代看起來不錯,那麼當數組存儲對對象信息的引用而不是所有不同的字符串int和double時,Array異常如何發生。

public void loadList(String fileName) throws FileNotFoundException 
    { 
    fileName = "stock1.txt"; 
    Scanner input = new Scanner(new File(fileName)); 
    String newLine = null; 
    String name = null; 
    String identifier = null; 
    int quantity = 0; 
    double cost = 0.0; 
    double price = 0.0; 
      while (input.hasNextLine() && d_nextItem < MAX_ITEMS) 
      { 
        if(input.hasNext()) 
        { 
          name = input.next(); 
        } 
        if(input.hasNext()) 
        { 
          identifier = input.next(); 
        } 
        if(input.hasNextInt()) 
        { 
          quantity = input.nextInt(); 
        } 
        if(input.hasNextDouble()) 
        { 
          cost = input.nextDouble(); 
        } 
        if(input.hasNextDouble()) 
        { 
          price = input.nextDouble(); 
        } 

        d_list[d_nextItem]= new Stock(name,identifier,quantity,cost,price); 
        newLine = input.nextLine(); 
        d_nextItem += 1; 
      } 
} 

回答

0

這個錯誤意味着你沒有傳遞參數給程序。

args是一個包含傳遞給程序的參數的數組,索引0超出邊界意味着沒有參數。

如何完成此操作取決於您如何運行程序。

0

args[]數組很特別,在您使用它時,通常會從命令行調用程序的更多信息。

適當的方法來填充args[]情況如下:

java Inventory classname.txt 

這樣,Java將拉classname.txtargs[0]

+0

哇...........這就是我做錯了,我甚至沒有意識到它,直到我讀你的評論。多虧了這一點,我才能夠繼續解決我遇到的其他問題。謝謝。 – DantesLightning

0

從我看到的,你粘貼在這裏的代碼看起來很好。所以問題可能在別處。 但是,一些快速更改可能會解決您的問題。 使用列表而不是數組用於庫存: List stocklist = new ArrayList(); stocklist.add(...);

並使d_nextItem成爲局部變量並在while循環之前對其進行初始化。

+0

當這個程序在課堂上被分配給我們時,我們沒有進入數組列表。目前正在進行數組列表,我相信我們的下一個任務將是這個任務的變體,但是使用數組列表。 – DantesLightning