こんにちは、文中の単語をカウントする際に再帰関数を使用する方法に関する Java コードを教えてもらえますか? 再帰を理解するのはちょっと難しいです多分コードは私が理解するのを助けるでしょうありがとう
2412 次
3 に答える
1
あなたが求めたものの実際の例は次のとおりです。
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Sample class to demonstrate recursion
* @author vmarche
*/
public class WordCount {
public static void main (String [] args) {
// Infinite loop
while (true) {
System.out.println("Please enter a sentence:");
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
try {
String input = keyboard.readLine();
int count = countWords(input);
System.out.println("Number of words: " + count);
}
catch (Exception e) {
System.exit(0);
}
}
}
/**
* Counts the words in a sentence recursively
* @param sentence The input sentence
* @return The number of words
*/
public static int countWords (String sentence) {
if (sentence.isEmpty())
return 0;
// Find the first index of a space
int space = sentence.indexOf(" ");
// If space exists, return count of sub-sentence
if (space != -1)
return 1 + countWords(sentence.substring(space + 1));
// Else space does not exist, return 1
else
return 1;
}
}
于 2013-06-15T03:07:34.383 に答える
0
これは再帰関数の非常に珍しい使用例ですが、基本的な考え方は次のようになります。
def countWordsIn (sentence):
if sentence.hasNoMoreWords():
return 0
return 1 + countWords (sentence.stripFirstWord())
あなたが本当に学ばなければならないのは、再帰には、より単純な場合 (文の単語数が、最初の単語を除いた文の単語数に 1 を追加するなど) の観点から問題を記述し、終了条件 (どこでもう言葉はありません)。
于 2013-06-15T02:38:20.313 に答える
0
public class RecursionDemonstration{
public static int numWords(String sentence)
{
int i = sentence.indexOf(' ');
if (i == -1) return 1; //Space is not found
return 1+numWords(sentence.substring(i+1));
}
public static void main(String[] args) {
System.out.println(numWords("Hello this is a test"));
}
}
コンセプトは、直接解決できるほど些細なものになるまで、問題のサイズをゆっくりと縮小することです。
必要なのは、基本ケースと、問題とサブ問題の間の関係だけです。
(PS: 私のコードは、空の文字列やスペースで終わる文では機能しません。簡単に修正できますが、簡単にするために修正しませんでした)。
于 2013-06-15T02:44:57.070 に答える