简体   繁体   中英

Java string Out of bounds foolishness

I am reading from a file and on one of the lines within the file reads: "{a,b,c,d}" I ran a split function on that line which returned a string array of 10(not sure why 10 instead of 9) elements. Each element being one character long. I then did a foreach loop over that array and within the body of that loop, I am doing a check to see if that "char" is a letterOrDigit and if it is.. do something else. But Within the first iteration of that loop, I get a StringIndexOutOfBounds Exception and for the life of me I do not know Why. I did not run into this issue while using intelliJ. This is being ran in eclipse and it's driving me nuts. Please help.

 for(int line = 1; line < file.size(); line++) // start at line 1 cause the line with the alphabet is useless.
    {
        if(line == 1) // Line 1 is always the states... so create the states.
        {
            String[] array = file.get(line).split("");
            for(String str :array) // split returns a string Array. each element is is one char long
            {
                // we only care about the letters and not the '{' or the ','
                if (Character.isLetterOrDigit(str.charAt(0))) {
                    dfa.addState(new State(str.charAt(0)));
                }
            }
        }

This is a screenshot of what the String array looks like after the split

This is what the line looks like after the file has been read.

The first string in the array is an empty string: "". It has a length of 0 so str.charAt(0) is out of bounds.

I think you don't need to use spilt function, you want to read whole stuff char by char just like array access. Empty value to string split function produces extra element because spilt function has no special case handling for such case, although it does handle case properly when length of split string is 1

You can rewrite your code something thing below

for (int line = 1; line < file.size(); line++) // start at line 1 cause the line with the alphabet is useless.
    {
        if (line == 1) // Line 1 is always the states... so create the states.
        {
            String lineValue = file.get(line);
            int len = lineValue.length();
            for (int index = 0; index < len; index++) {
                if (Character.isLetterOrDigit(lineValue.charAt(index))) {
                    //dfa.addState(new State(str.charAt(0)));
                }
            }
        }
    }

From your screenshot, the array element at the index 0's length is 0, ie it's a empty String, but during iteration you're trying to access the first char of empty String, so it throws the IndexOutOfBoundException .

To avoid this check the length or isEmpty before accessing it's char

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM