Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Java For condition statement seemed to be ignored?

Tags:

java

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.

like image 574
euUbsd36R Avatar asked Feb 13 '23 06:02

euUbsd36R


1 Answers

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.

like image 139
Sotirios Delimanolis Avatar answered Mar 07 '23 21:03

Sotirios Delimanolis