2017-01-28 11 views
-1

こんにちは、私はこれほど新しくなっています。私があまりにも素朴であれば、私を許してください。文中に「will」という言葉を見つけよう。

私はちょうどJavaで始まっていますので、私は答えを探していませんが、もしあなたが少なくとも正しい方向に私を指すことができるなら、それは素晴らしいでしょう!

私は文章で "will"という単語を見つけようとしています。これは私がこれまでに行うために管理しているものです

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

:ここ

は、以下のコードです。答えは1になりますが、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")); 
+0

質問をする前に、SOで検索してください。すでに多くの回答があります。 – OldProgrammer

答えて

1

「occurrencesOfWord」メソッドで次のように試してみてください。

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

return i; 
+1

おかげでうまくいった!パターンやマッチャーが何をしているのかを説明することができます。 –

関連する問題