首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java对象数组越界问题

Java对象数组越界问题
EN

Stack Overflow用户
提问于 2012-02-22 13:36:02
回答 2查看 198关注 0票数 1

我尝试将输入文件中的数据存储到一系列对象中,然后将这些对象存储在一个数组中。问题是它给了我一条错误消息,说我的数组越界了。

它可以毫无问题地从文件中获取数据,但我不知道为什么。

下面是我得到的信息:

代码语言:javascript
复制
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]);
        }
    }
}

下面是输入:

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-02-22 13:49:37

考虑一下这一行-

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

这将存储在tempString中。当你这样做的时候

代码语言:javascript
复制
  String[] tempArray = tempString.split(",");

为了这个,那么

tempArray -> B

tempArray1 -> C124.S17

tempArray2 ->帽子里的猫

tempArray3 ->博士

tempArray4 ->儿童文学

没有tempArray5!

因此,当你说

代码语言:javascript
复制
    bookObject[i] = new Books(temp, tempArray[1],tempArray[2], tempArray[3], tempArray[4], tempArray[5]);

它将抛出ArrayIndexOutOfBoundsException,因为tempArray的最大数组索引是4而不是5。

票数 1
EN

Stack Overflow用户

发布于 2012-02-22 13:41:29

我的猜测是,temp数组中包含的项比您预期的要少。尝尝这个。

代码语言:javascript
复制
    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]);
    }

它应该会告诉你有多少个项目。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9389596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档