Thursday, August 11, 2011
Why when you choose to use the for method in java instead of the while- method, you get StrinIndexoutofbound?
I don't think you've written your code correctly. Remember, index is declared outside of the first while loop, but is incremented inside BOTH while loops. And although the outer while loop carefully checks and exits if you reach the end of the string, the inner while loop does NOT. So, if the last character of the string is anything other than '|', the inner while loop will enter properly, increment index up to the length of the string, then when it tries to check its loop condition with index==all.length() it will try to access a character past the end of the string, whereupon Java throws an exception. One simple way to fix this would be to put the same length check in the outer while loop into the inner while loop as well, orred with the existing condition.
No comments:
Post a Comment