我尝试将输入文件中的数据存储到一系列对象中,然后将这些对象存储在一个数组中。问题是它给了我一条错误消息,说我的数组越界了。
它可以毫无问题地从文件中获取数据,但我不知道为什么。
下面是我得到的信息:
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]);
}
}
}下面是输入:
4
B,C124.S17,The Cat in the Hat,Dr. Seuss,Children’s Literature
P,QJ072.C23.37.4,Computational Linguistics,37,4,Computational Linguistics
P,QJ015.C42.55.2,Communications of the ACM,55,2,Computer Science
B,F380.M1,A Game of Thrones,George R. R. Martin,Fantasy Literature发布于 2012-02-22 13:49:37
考虑一下这一行-
B,C124.S17,《戴帽子的猫》,苏斯博士,儿童文学
这将存储在tempString中。当你这样做的时候
String[] tempArray = tempString.split(",");为了这个,那么
tempArray -> B
tempArray1 -> C124.S17
tempArray2 ->帽子里的猫
tempArray3 ->博士
tempArray4 ->儿童文学
没有tempArray5!
因此,当你说
bookObject[i] = new Books(temp, tempArray[1],tempArray[2], tempArray[3], tempArray[4], tempArray[5]);它将抛出ArrayIndexOutOfBoundsException,因为tempArray的最大数组索引是4而不是5。
发布于 2012-02-22 13:41:29
我的猜测是,temp数组中包含的项比您预期的要少。尝尝这个。
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]);
}它应该会告诉你有多少个项目。
https://stackoverflow.com/questions/9389596
复制相似问题