4
函数countHi计算给定字符串中“hi”的数量。如果用“abc hi ho”作为参数调用countHi,则i在循环之前首先设置为4。我在第一个循环内重置为-1。第1次循环后,条件(i!= -1)为假,整个条件语句为假。我期望例程会退出循环,但它不会,我不明白为什么。为什么Java For条件语句似乎被忽略?
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;
}
在接下来的版本中,条件正确退出循环:
for (; i!=-1;) {
cnt++;
i = str.indexOf("hi", i + 1);
}
版本更经济,但是这将是很好理解为什么第一个版本产生了意想不到的结果。