Why was the Java For condition expression ignored?

The countHi function counts the number of "hi" in a given string. If countHi is called with the parameter "abc hi ho" as the parameter, I am first set to 4, and then for the loop. I reset to -1 within the 1st loop. After the 1st cycle, the condition (i! = -1) is false, and the operator of the whole condition is false. I expect the procedure to exit the loop, but it is not, and I do not 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 next version, the condition exits the loop correctly:

for (; i!=-1;) {
        cnt++;
        i = str.indexOf("hi", i + 1);
    }

The editors are more economical, but it would be nice to understand why the first version gives an unexpected result.

+4
source share
1 answer

imay become -1of

i = str.indexOf("hi", i + 1);

but

i++

for 0 .

+8

Source: https://habr.com/ru/post/1535787/


All Articles