OOP库存计划

时间:2014-03-05 03:57:47

标签: java arrays indexoutofboundsexception

我收到的错误是一个数组索引超出范围的异常,但我不知道它为什么会发生这种情况。

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");
    }

特定错误是线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:0在Inventory.main(Inventory.java:27),它指向main中的inventory.loadList方法。只有在运行程序时才出现错误,我不知道为什么会发生这种错误。

这是loadList方法,并且迭代看起来不错,所以当数组存储对象信息的引用时,如何发生Array异常,而不是所有不同的字符串,int和double。

  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;
            }
}

3 个答案:

答案 0 :(得分:0)

该错误意味着您没有将参数传递给程序。

args是一个包含传递给程序的参数的数组,索引0超出范围的事实意味着没有参数。

如何做到这一点取决于你如何运行程序。

答案 1 :(得分:0)

args[]数组的特殊之处在于,当您使用它时,您通常会从命令行调用具有更多信息的程序。

填充args[]的适当方法如下:

java Inventory classname.txt

这样,Java会将classname.txt拉入args[0]

答案 2 :(得分:0)

从我看到的,你在这里粘贴的代码看起来很好。所以问题可能在其他地方。 但是,一些快速更改可能会解决您的问题。 使用列表而不是库存数组: List stocklist = new ArrayList(); stocklist.add(...);

并使d_nextItem成为局部变量并在while循环之前初始化它。