Makri
Makri

Reputation: 341

Getting arrayindexoutofbounds when reading from file

I have this small problem of mine, where I would be getting arrayindexoutofboundsexception when trying to read from file. I don't know of a better or more detailed way of explaining it, so I will paste the code and the error below. This is all in the mainmethod of my program.

    File fila;
    String[] innlesningsarray=new String[500];

    try{
        Scanner innFil=new Scanner(new File("/uio/hume/student-u77/makrist/Downloads/akronymer.txt"));

        while(innFil.hasNext()){
        for(int i=0; i<500; i++){

        // String innLest=br.nextLine();
            innlesningsarray=innFil.nextLine().split("\t");
            System.out.println(innlesningsarray[i]);
            System.out.println(innFil.nextLine());
        }
        System.out.println("test");
        }
        System.out.println("Test2");

    } catch(Exception e){
        System.out.print(e);
    }
    }
}

After this part I have an object of Acronyms and stuff, but no errors there...

The error:

AA Auto Answer

AAB All-to-All Broadcast

java.lang.ArrayIndexOutOfBoundsException: 1

Upvotes: 0

Views: 148

Answers (1)

Joetjah
Joetjah

Reputation: 6132

You do nextLine() twice in the loop. This will read 2 lines in your file.

while(innFil.hasNext()) can return true if you have 1 line left. Next thing you do is reading 2 lines in that while-loop. Since there is only 1 line left, you'll get your exception.

You have it placed in a for-loop as well. That means you do 500*2 times the readLine() method, while you only check for 1 line.

Try the following:

try{
    Scanner innFil=new Scanner(new File("/uio/hume/student-u77/makrist/Downloads/akronymer.txt"));

    while(innFil.hasNext()){
        for(int i=0; i<500; i++){
            String theReadLine = innFil.nextLine();
            innlesningsarray=theReadLine.split("\t");
            System.out.println(innlesningsarray[i]);
            System.out.println(theReadLine);
        }
        System.out.println("test");
    }
    System.out.println("Test2");

    } catch(Exception e){
        System.out.print(e.printStackTrace);
    }
}

This solves a possible error with the nextLine() method. You should be sure innlesningsarray actually has 500 or more entries, else you will receive your exception. Make sure that your akronymer.txt file has the string \t 500 or more times in it!

I also changed your catch-code. Instead of print(e) you should write e.printStackTrace(). This will print a lot of useful information about the exception. Thanks to Roland Illig for that comment!

Upvotes: 2

Related Questions