문제

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.

도움이 되었습니까?

해결책 2

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

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

다른 팁

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++; }

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top