Function countHi counts the number of "hi" in a given string. If countHi is called with "abc hi ho" as parameter, i is first set to 4, before for loop. i reset to -1 within 1st loop. After 1st loop, condition (i != -1) is false, and whole condition statement is false. I expect routine will exit loop, but it does not, and I don't understand why.
public static int countHi(String str) {
int cnt = 0;
int i = str.indexOf("hi");
for (; (i < str.length()) && (i != -1); i++) {
cnt++;
i = str.indexOf("hi", i + 1);
}
return cnt;
}
In the following version, the condition exits loop correctly:
for (; i!=-1;) {
cnt++;
i = str.indexOf("hi", i + 1);
}
Revision is more economical, but it would be nice to understand why first version produces an unexpected result.
i
might become -1
from
i = str.indexOf("hi", i + 1);
but
i++
in the for
loop update expression will bring it back to 0 before the condition is checked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With