Nacht
Nacht

Reputation: 11346

I keep getting a "ArrayIndexOutOfBounds" Exception when using String.split

I am writing this class for another program and I keep getting an Array out of bounds exception when I am splitting the string str.

    static String[][] readFile(){
    BufferedReader in;
    count = 0;
    String[][] ret = new String[20][2];
    try
    {
        in = new BufferedReader(new FileReader(CFGfolder+"\\input.ini"));
        String str;

        while((str=in.readLine()) != null){
            if(str!="[GameEvents]"){
                ret[count][0]=str.split("=")[0];
                ret[count][1]=str.split("=")[1];
                count++;
            }
        }
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return ret;

}

This is the format of the file it is reading.

evtCastSpell1=[q]
evtCastSpell2=[w]
evtCastSpell3=[e]
evtCastSpell4=[r]

I tried seeing what the str string really is (meaning, print it without the splitting) and it shows that it is correctly reading the file and putting it in the array. The problem comes when I try to read the [1] of the splitted string. The [0] is fine and it correctly prints

evtCastSpell1
evtCastSpell2
evtCastSpell3
evtCastSpell4

I really have no idea why it is not reading the [1] part. Usually this kinds of errors come from regex expressions, is it understanding the [ in the second part as a regex expression? How would I get around that if so? I've tried looking around but all I can find is similar errors that happen because of regex expressions. Is this one the same?

Thank you for your help.

Upvotes: 0

Views: 277

Answers (2)

Buhake Sindi
Buhake Sindi

Reputation: 89169

You are doing a reference equality comparison instead of a string equals() comparison:

I would do this:

while((str=in.readLine()) != null){
    if(!"[GameEvents]".equals(str)) {
        String[] splits = str.split("=");
        ret[count][0]=splits[0];
        ret[count][1]=splits[1];
        count++;
    }
}

The reason of you ArrayIndexOutOfBoundsException is because of this:

if(str!="[GameEvents]"){

Because of the reference equality, the if expression returns a true and you're doing a split() on the value [GameEvents].

I hope this helps:

Upvotes: 2

sudmong
sudmong

Reputation: 2036

The reason for the exception could be the number of lines in file going more than the size of your array. Also replace this if(str!="[GameEvents]") with if(!str.equals("[GameEvents]")) for getting correct results.

Upvotes: 4

Related Questions