-1

Hi guys I am quite new to this so please forgive me if I am being too naive.

I am just starting in Java so I am not looking for an answer, but if you can at least point me in the right direction that would be great!.

I am just trying to find the word "will" in a sentence.

here is the code below:

String input =
          "You have brains in your head "
        + "You have feet in your shoes "
        + "You can steer yourself "
        + "Any direction you choose "
        + "You're on your own And "
        + "you know what you know "
        + "And YOU are the guy who’ll "
        + "decide where to go "
        + "You’ll get mixed up "
        + "of course, as you already know "
        + "You’ll get mixed up with "
        + "many strange birds as you go "
        + "So be sure when you step "
        + "Step with care and great "
        + "tact and remember that "
        + "Life’s A Great Balancing Act "
        + "And will you succeed "
        + "Yes You will indeed "
        + "ninety eight and three quarter percent guaranteed "
        + "KID YOU’LL MOVE MOUNTAINS ";

This is what I have managed to do so far. but I keep getting the answer 1 but it should be 2.

public Integer occurrencesOfWord(String word)

          {

              int wordCount = 0;


              if(input.indexOf(word) >=0)
              {
                 wordCount++; 
              }

                 return wordCount;
          }




System.out.println("Occurences of word 'will': " + mainClass.occurrencesOfWord("will"));
OldProgrammer
  • 12,050
  • 4
  • 24
  • 45

1 Answers1

1

Try something like following in your method 'occurrencesOfWord'.

int i = 0;
Pattern p = Pattern.compile(word);
Matcher m = p.matcher( input );
while (m.find()) {
    i++;
}

return i;
VHS
  • 9,534
  • 3
  • 19
  • 43