Java-对象数组越界问题
我试图将输入文件中的数据存储到一系列对象中,然后这些对象存储在一个数组中。问题是它给了我一条错误消息,说我的数组超出了范围 它从文件中获取数据没有问题,但我不知道为什么 以下是我得到的:Java-对象数组越界问题,java,Java,我试图将输入文件中的数据存储到一系列对象中,然后这些对象存储在一个数组中。问题是它给了我一条错误消息,说我的数组超出了范围 它从文件中获取数据没有问题,但我不知道为什么 以下是我得到的: public static void main(String[] args) throws IOException { Scanner scan = new Scanner(new File("input.txt")); Scanner keyboard = new Scanner(System
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(new File("input.txt"));
Scanner keyboard = new Scanner(System.in);
int numItems = scan.nextInt();
scan.nextLine();
Books bookObject[] = new Books[numItems];
Periodicals periodicalObject[] = new Periodicals[numItems];
for(int i = 0; i < numItems; i++)
{
String tempString = scan.nextLine();
String[] tempArray = tempString.split(",");
if(tempArray[0].equals("B"))
{
char temp = 'B';
//THIS IS WHERE THE IDE SAYS THE ERROR IS
bookObject[i] = new Books(temp, tempArray[1],tempArray[2], tempArray[3], tempArray[4], tempArray[5]);
}
else if(tempArray[0].equals("P"))
{
char temp = 'P';
periodicalObject[i] = new Periodicals(temp, tempArray[1], tempArray[2], tempArray[3], tempArray[4], tempArray[5]);
}
}
}
我猜临时数组中的项目比您预期的要少。试试这个
if(tempArray[0].equals("B"))
{
char temp = 'B';
//THIS IS WHERE THE IDE SAYS THE ERROR IS
System.out.println(tempArray.length);
bookObject[i] = new Books(temp, tempArray[1],tempArray[2], tempArray[3], tempArray[4], tempArray[5]);
}
它应该告诉你有多少物品 考虑这条线-
B、 C124.S17,《帽子里的猫》,苏斯博士,儿童文学
这将存储在tempString中。当你这样做的时候
String[] tempArray = tempString.split(",");
那么,为了这个
tempArray[0]->B
tempArray[1]->C124.S17
tempArray[2]->帽子里的猫
tempArray[3]->Seuss博士
tempArray[4]->儿童文学
没有临时数组[5]
所以你说
bookObject[i] = new Books(temp, tempArray[1],tempArray[2], tempArray[3], tempArray[4], tempArray[5]);
它将抛出ArrayIndexOutOfBoundsException,因为tempArray的最大数组索引是4而不是5 提出技术问题101:1。显示错误。2.显示您的输入。:-)堆栈溢出!=Java调试者哦,很抱歉在编程板Lior上请求编程帮助。下次我会三思而后行。我在构造函数中发现了一个问题(我本应该只取5个参数,但我取了6个),现在我没有得到那个错误。然而,现在我有另一个问题,在我的输入文件中找不到一行。。。奇怪的谢谢,是的,修复了它,我注意到我的构造函数写错了,所以我用了太多的参数。
bookObject[i] = new Books(temp, tempArray[1],tempArray[2], tempArray[3], tempArray[4], tempArray[5]);