While loop doesn't run a indexOf search

拟墨画扇 提交于 2019-12-02 23:37:20

问题


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 0 for my "appearance" variable, which should store how many times "ea" appears in wordTwo.

Here's the relevant code section:

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);

回答1:


What do you mean by

 appearances = appearances++;

This will make sure appearances is ZERO always.

Shouldn't it be just appearances++ ?




回答2:


The problem is where you set the value of appearances. There's a difference between

appearances = appearances++;

and

appearances = ++appearances;

What you have will assign the value of appearances and then increment the 'old' appearances variable. You're going to want to increment it and then assign it.

Alternatively, you could just write

appearances++;



回答3:


There are two bugs here.

One is that you've written appearances = appearances++; instead of just appearances++;. The effect of this is that appearances is incremented, and then reset to its previous value; in other words, there's no change.

The second bug is that you're beginning each search after the first, at the location where the match was found. So you're just finding the same match over and over. Your output will just therefore depend on how many times you can subtract positionCount before wordTwoLength becomes negative.

Here is how I would write this method, if I had to.

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++;
    } 
}



回答4:


I think this may be your problem. The line "appearances = appearances++;" will, in your case, set appearances to 0. This is because the ++ operator increments the variable but returns the original number. You just want to put "appearances++;".

I.e. it takes appearances (which is 0) adds 1 to it (making its value 1)and then returns 0. So basically the statement is equivalent to "appearances = 0;".



来源:https://stackoverflow.com/questions/19395153/while-loop-doesnt-run-a-indexof-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!