错误的界外例外

时间:2014-09-25 07:45:58

标签: java windows for-loop indexoutofboundsexception

所以,我已经从文本文件中检索了一行,并将其作为字符串数组中的一个字符串存储,我将其称为inventorylist [i]。然后我使用.split("")将其拆分并存储名为invlistTokens的数组中的标记。当我对该令牌数组执行任何操作时,它会抛出一个超出范围的异常。如果我将它放在forloop中以显示我期望的5个令牌,它将成功读取它们然后抛出该异常。

    public static item[] loadInv(){
    String inventoryname = "Henderson_j_inv.txt";
    String[] inventorylist= new String[50]; //more than enough room for the file to load in
    String[] invlistTokens = new String [5];
    item[] inventory = new item[50];

    try {
        ReadFile file = new ReadFile(inventoryname);
        inventorylist = file.OpenFile();
    } catch (IOException e) {
        System.out.print("FILE FAILED TO LOAD");
    }

    for(int i=0; i< Array.getLength(inventorylist); i++){
        System.out.println(inventorylist[i]);//This always succeeds
        invlistTokens=inventorylist[i].split(" ");

        for(int j=0; j<5; j++){  //This is the weird ForLoop. It completes and then java throws out of bounds.
            System.out.println(invlistTokens[j]);
        }
    }

请原谅我的杂乱帖子,这是我的第一篇文章,我不确定我对这种奇怪的错误有多具体

Eclipse屏幕截图:http://imgur.com/ssArryd

Eclipse Screenshot

我确实在我的实际代码中得到了变量,恰好在将forloop添加到帖子时是假人

这是实际的异常,除了我知道它使它超过1.循环在它抛出之前完成所有5次运行。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at shopping2.loadInv(shopping2.java:50)
    at shopping2.main(shopping2.java:23)

所以我把代码更改为

public static item[] loadInv(){
    String inventoryname = "Henderson_j_inv.txt";
    String[] inventorylist= new String[50];
    String[] invlistTokens = new String [100];
    item[] inventory = new item[50];

    try {
        ReadFile file = new ReadFile(inventoryname);
        inventorylist = file.OpenFile();
    } catch (IOException e) {
        System.out.print("FILE FAILED TO LOAD");
    }

    System.out.print(inventorylist.length); //This displays 19, when it should be giving me 10 based on my file

    for(int i=0; i< inventorylist.length; i++){
        //System.out.println(inventorylist[i]);
        invlistTokens=inventorylist[i].split(" ");
        System.out.println(invlistTokens.length); //This alternates between 5 and 1


    }

所以我认为问题出在我的txt文件或读者类中。感谢大家的帮助。

2 个答案:

答案 0 :(得分:1)

我们在堆栈跟踪之前看到两个\n,似乎用空字符串调用System.out.println()两次。

所以似乎在i的第二次迭代中,inventorylist[i]是一个空字符串。因此.split(" ")返回索引为0的空字符串的单元素数组。

这就是为什么在j的第二次迭代中,您在索引ArrayIndexOutOfBoundsException处有一个1

答案 1 :(得分:1)

您的文字来源包含两行!

第一行是屏幕截图中的一行:

  

01 MusicCD 100 20 5.00

第二个是一个简单的空行。

所以你的小程序在第一行上正确循环,打印出正确的结果。然后它循环遍历第二行(空)并执行以下操作:

  1. 打印出空行。看看你的截图。它包含这个写的空行。
  2. 按空格分割此空字符串,生成1个元素数组。
  3. 在这个1元素数组上循环,正确打印出第一个元素(另一个空行 - >查看截图)。
  4. 正确地为索引1抛出AIOOBE,因为没有这样的索引。
  5. 结论:在进入循环之前检查空行。或者检查分割数组中的元素数量。