Java 面向对象清单程序
我收到的错误是一个数组索引越界异常,但我不知道为什么它发生在它所在的位置Java 面向对象清单程序,java,arrays,indexoutofboundsexception,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
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方法,迭代看起来没有错,所以当数组存储对对象信息的引用时,而不是所有不同的字符串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;
}
}
public void loadList(字符串文件名)引发FileNotFoundException
{
fileName=“stock1.txt”;
扫描仪输入=新扫描仪(新文件(文件名));
字符串换行符=null;
字符串名称=null;
字符串标识符=null;
整数数量=0;
双倍成本=0.0;
双倍价格=0.0;
while(input.hasNextLine()&&d_nextItem
该错误表示您没有向程序传递参数
args
是一个包含传递给程序的参数的数组,索引0超出范围意味着没有参数
具体如何操作取决于您运行程序的方式。args[]数组的特殊之处在于,当您使用它时,您调用程序时通常会从命令行获取更多信息 填充
args[]
的适当方法如下:
java Inventory classname.txt
通过这种方式,Java将
classname.txt
拉入args[0]
据我所见,您粘贴在这里的代码看起来很好。所以问题可能在别处。
不过,一些快速的更改可能会解决您的问题。
对库存使用列表而不是数组:
List stocklist=new ArrayList();
股票列表。添加(…)
将d_nextItem设为局部变量,并在while循环之前对其进行初始化。Wow……….这就是我做错的地方,直到读到你的评论我才意识到这一点。多亏了这一点,我才得以继续前进并解决我遇到的其他问题。谢谢。当这个程序在课堂上分配给我们时,我们还没有进入数组列表。现在我们正在检查数组列表,我相信我们的下一个任务将是这个任务的一个变体,但是使用数组列表。