最后一行造成了问题。
lastIndex永远不会为-1,所以会有无限循环。可以通过将代码的最后一行移到if块中来解决此问题。
String str = "helloslkhellodjladfjhello";String findStr = "hello";int lastIndex = 0;int count = 0;while(lastIndex != -1){ lastIndex = str.indexOf(findStr,lastIndex); if(lastIndex != -1){ count ++; lastIndex += findStr.length(); }}System.out.println(count);


