简体   繁体   中英

Can't figure out why I'm getting a StringIndexOutOfBoundsException

I have the following code

while (input.hasNextLine()) {
    String line = input.nextLine();
    System.out.println(line);  // added to test if anything in String, and there is
    int whiteSpace = 0;
    int j = 0;

    while (Character.isWhitespace(line.charAt(j))) {
        whiteSpace++;
        j++;
    }
}

When I run it, I get a StringIndexOutOfBoundsException: String index out of range: 0 , which makes no sense to me. I added a System.out.print(line) to test if there is anything in the String and there is. I tried initializing j with higher values, still get same thing, just a different String index out of range: ? . Does anyone know why I'm getting this exception? Makes no sense to me.

Try something more like this:

while(j<line.length) {
    if(Character.isWhitespace(line.charAt(j))) {
        whiteSpace++;
    }
    j++;
}

It's probably closer to what you're trying to do. What you have now, if it worked, would only increment j whenever there was a whiteSpace , and as such, even if you weren't getting the error, you'd be stuck in an infinite loop unless you had a String that consisted of only white spaces. The above code will increment j on every character (so you check each character once and only once through the entire string), but increments whiteSpace only when Character.isWhitespace(line.charAt(j)) returns true .

EDIT: Given the re-clarification of what you're actually trying to do, just drop the variable j as it muddies the readability (hence my confusion).

while(whiteSpace<line.length && Character.isWhitespace(line.charAt(whiteSpace)))
    { whiteSpace++; }

I don't know what's in your line, but you should try :

while (j < line.length() && Character.isWhitespace(line.charAt(j))) {
    whiteSpace++;
    j++;
}

Maybe because you are incrementing j++ and then using it in :

Character.isWhitespace(line.charAt(j))

If you only have one char on the line, which is a whitespace, then on the next iteration, it would try to reach next char, which doesn't exist.

Hence you might have to check if char is not null, and then if it is a whitespace. Or brake if the next char is null.

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