我收到的錯誤是一個數組索引越界異常,但我不知道它爲什麼發生在它的位置。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;
}
}
哇...........這就是我做錯了,我甚至沒有意識到它,直到我讀你的評論。多虧了這一點,我才能夠繼續解決我遇到的其他問題。謝謝。 – DantesLightning