String Index Out Of Bounds Exception [duplicate]
I am really stuck on this exception
private static void getUserComment(String s) {
while(s.contains("author'>")){
S开发者_运维百科ystem.out.println(s.substring(s.indexOf("author'>"),
s.indexOf("<div id='")));
s = s.substring(0, s.indexOf("author'>")) +
s.substring(s.indexOf("<div id='"+9));
}
}
You should use a proper parser or at least do some regular expression pattern matching (which is already "bad enough" for HTML or XML).
That said, your "offset" of 9 is likely the indirect cause of the exception:
s.indexOf("<div id='"+9)
This will make a literal string <div id='9
which is not found; indexOf
then returns -1 and this causes the exception in the substring
method. Maybe you wanted to actually add 9 to the index like this? s.indexOf("<div id='")+9
Note that the function is useless anyways, changing s
will only change the local variable and not the original variable (parameters are by value in Java).
精彩评论