2012-02-22 86 views
1

我试图将输入文件中的数据存储到一系列对象中,然后存储在一个数组中。问题是它给了我一个错误消息,说我的数组超出了界限。Java - 对象数组越界问题

它从文件中获取数据没有问题,但我不知道为什么。

下面是我得到了什么:

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 
+0

询问技术问题101:1,显示错误。 2.显示你的输入。 :-) – 2012-02-22 05:39:01

+5

StackOverflow!= Java调试器 – 2012-02-22 05:39:05

+1

哦,很抱歉在编程板Lior上寻求编程帮助。下次我会考虑三次。 – mrowland 2012-02-22 05:50:32

回答

1

考虑这条线 -

B,C124.S17,戴帽子,博士猫。苏斯,儿童文学

这将被存储在tempString中。当你

String[] tempArray = tempString.split(","); 

对于这一点,那么

tempArray [0] - >乙

tempArray [1] - > C124.S17

tempArray [2] - >猫在帽子

tempArray [3] - >苏斯博士

tempArray [4] - >儿童文学

没有tempArray [5]!

因此,当你说

bookObject[i] = new Books(temp, tempArray[1],tempArray[2], tempArray[3], tempArray[4], tempArray[5]); 

它会抛出一个ArrayIndexOutOfBoundsException,因为tempArray最大数组索引是4,而不是5

+0

是的,修正了它,我注意到我的构造函数写错了,所以我的参数太多了。 – mrowland 2012-02-22 05:52:27

2

我的猜测是,临时数组中有较少的项目比您预期。尝试这个。

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

它应该告诉你有多少物品在那里。

+0

我在我的构造函数中发现了一个问题(我只是应该拿5个参数,但我拿6),现在我没有得到那个错误。但是,现在我有另一个问题,它没有在我的输入文件中找到一条线......很奇怪。谢谢 – mrowland 2012-02-22 05:49:09