while循环不运行indexOf搜索

我试图找出一个字符串出现在另一个字符串中的次数。 对于我的测试,我使用“ea”代替wordOne和“Ilikedthebestontheeastbeachleast”代表wordTwo。 我的输出为我的“外观”变量返回0,该变量应该存储在wordTwo中出现“ea”的次数。

这是相关的代码部分:

int wordTwoLength = wordTwo.length(); System.out.println(wordTwoLength); while (wordTwoLength > 0) { positionCount = wordTwo.indexOf(wordOne, positionCount); appearances = appearances++; wordTwoLength = (wordTwoLength - positionCount); } System.out.println(appearances); 

你是什​​么意思

  appearances = appearances++; 

这将确保外观始终为零。

难道不仅仅是外表++吗?

问题在于您设置外观的值。 两者之间有区别

 appearances = appearances++; 

 appearances = ++appearances; 

你拥有的将分配外观的值,然后增加’旧’外观变量。 您将要增加它然后分配它。

或者,你可以写

 appearances++; 

这里有两个错误。

一个是你写的appearances = appearances++; 而不仅仅是appearances++; 。 这样做的结果是appearances增加,然后重置为其先前的值; 换句话说,没有变化。

第二个错误是你在第一个搜索之后开始每个搜索,在找到匹配的位置。 所以你只是一遍又一遍地找到相同的比赛。 因此,您的输出将取决于在wordTwoLength变为负数之前可以减去positionCount wordTwoLength

如果必须的话,我将如何编写此方法。

 public int numberOfOccurrences(String toExamine, String toFind) { int currentPosition = 0; int occurrences = 0; for(;;) { int index = toExamine.indexOf(toFind, currentPosition); if (index == -1) { return occurrences; } currentPosition = index + toFind.length(); occurrences++; } } 

我想这可能是你的问题。 行“appearances = appearances ++;” 在您的情况下,将外观设置为0.这是因为++运算符递增变量但返回原始数字。 你只想把“外观++;”。

即外观(为0)将其加1(使其值为1)然后返回0.所以基本上该语句相当于“appearances = 0;”。