I was coding in commons lang earlier tonight when I found one of my test cases wasn't passing. It took a few minutes to realise my stupid error. So here's the test! Can you spot it too???
public int readToken(char[] chars, int start) { int pos = start; while (pos < chars.length) { if (chars[pos++] == '"') { return pos; } } return start++; }
(By the way, there are lots of possible errors here like NPE and this is a very simplified version of the actual method, however somewhere here is a particular 'weird' error.
Did you find it?
Its the return statement. You might think on glancing at the code that the method would return the value of start plus one. But it doesn't. It returns the value of start, as the ++ occurs after the return statement. Obvious really - yet in a non-obvious way. The fix of course is to do return ++start;
;-).
(Sorry if you got it straight away, but it amused me for a minute or two...)
The biggest problem I can see is the never ending while loop - you never increment 'pos'.
ReplyDeleteSorry my bad :-(
ReplyDeletepos corrected now to pos++
Wouldn't "return start+1" be more clear since you dont use the modified value afterwards?
ReplyDeleteYes, either
ReplyDeletereturn ++start;
or
return start + 1;
would work
And yes, the latter probably is clearer.