【发布时间】:2015-05-03 08:49:51
【问题描述】:
我创建了这个方法,但它只返回我的 txt 文件中的第一个单词。我需要递归遍历整个文本文件并返回带有传递参数“theC”的任何单词并忽略没有“theC”的单词的方法 任何帮助将不胜感激,谢谢。
public static String getWordsString(Scanner theFile, char theC)
{
String words = "";
if(theFile.hasNext())
{
String word = theFile.next();
if(word.indexOf(theC) != -1)
{
words += word;
}
getWordsString(theFile, theC);
}
return words;
}
示例:System.out.println(getWordsString(scanner, 'c'));
将返回 txt 文件中带有字符 c 的任何单词
【问题讨论】:
-
为什么要在这里使用递归?一个简单的循环更有意义。
-
第一个为什么要递归?第二个这不是更合乎逻辑
return words+ getWordsString(theFile, theC);?? -
好吧,你忽略了递归调用返回的
words。你期待什么? -
@Abdelrahman Elkady 2nd 实际上看起来像一个解决方案,因此更合乎逻辑。