String index out of bound exception in if statement

199 views Asked by At
if(line.get(count).substring(line.get(count).indexOf(p1)).equals(p1.substring(0, p1.indexOf(" ")))) {
    count++;
    if(line.get(count).contains(p1.substring(p1.indexOf(" ") + 1, p1.length())))
        System.out.println((count-1) + "     " + (line.get(count-1).indexOf(p1)) + "     " + p1);
}

Line is the array list with size of 65008, I'm trying to test of a name appear on two line of the file, with the first name appears on one line and the last name appears on the second line.however, the index out of bound exception occurs at the first if statement. I'm unable to realize if I did something wrong here to cause this problem as I was trying to compare the substrings.Can anyone suggest a way to solve this issue? These if statements is quite long, but I will try to tweak them later.

1

There are 1 answers

0
Japheth Ongeri - inkalimeva On

Try using this code:

        if (line.get(count).substring(line.get(count).indexOf(p1))
            .equals(p1.substring(0, p1.indexOf(" ")))) {
        if (line.get(count).contains(
                p1.substring(p1.indexOf(" ") + 1, p1.length()))) {
            System.out.println((count - 1) + "     "
                    + (line.get(count - 1).indexOf(p1)) + "     " + p1);
        }
        count++;
    }

The main difference is that it increments count after both if conditions have run also added braces to the second if for readability. I'm not sure this will solve the problem, if not then you may need to provide more information.