本文介绍了使用indexOf的while循环输出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出一个字符串在另一个字符串中出现了多少次.对于我的测试,我对单词One使用"ea",对于单词Two使用"Ilikedthebestontheeastbeachleast".我的输出为我的"appearance"变量返回2,该变量应存储在"wordTwo"中出现"ea"的次数.它应该返回3.

I'm trying to find out how many times one string appears in another. For my testing, I'm using "ea" for wordOne and "Ilikedthebestontheeastbeachleast" for wordTwo. My output is returning 2 for my "appearance" variable, which should store how many times "ea" appears in wordTwo. It should return 3.

我试图弄乱变量的初始化,并尝试以不同的方式思考数学,但是我几乎没有想法.

I've tried messing with variable initializations, and trying to think of the math differently, but I'm pretty much out of ideas.

这是相关的代码部分:

  int wordTwoLength = wordTwo.length();
  System.out.println(wordTwoLength);

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

谢谢!

我忘了补充说,我尝试了其他测试输入并得到了疯狂的输出.返回的数字将比某些数字高,而另一些数字低.

I forgot to add that I tried other test inputs and got crazy outputs. It would return numbers way higher than expected for some, and lower for others.

推荐答案

因此,现在的问题是.indexOf仍然在wordTwo中返回"ea"的真实索引-它没有考虑您从哪里开始.另外,将positionCount设置为等于您找到单词的位置,然后从该位置再次搜索只会使您立即找到该单词的相同实例,而不是下一个.

So now the problem is that .indexOf still returns the true index of "ea" in wordTwo - it doesn't take into account where you start from. Also, setting positionCount equal to where you find the word and then searching from that position again is just going to make you immediately find the same instance of that word, not the next one.

wordTwo中"ea"的第一个实例的索引为18,因此wordTwoLength将设置为32-18或14.然后您将在wordTwo中找到相同的ea实例,并将wordTwoLength设置为14-18或-4.然后您将退出while循环,其外观为2.

The index of the first instance of "ea" in wordTwo is 18, so wordTwoLength will be set to 32-18, or 14. Then you'll find the same instance of ea in wordTwo, and wordTwoLength will be set to 14-18, or -4. Then you'll exit the while loop, with appearances being 2.

这篇关于使用indexOf的while循环输出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 05:04