[英]Why aren't my words coming out less than 8 characters?
public String compWord() throws IOException, ClassNotFoundException
{
// Local constants
final int MAX_COUNT = 8;
// Local variables
BufferedReader reader = new BufferedReader(new FileReader("dictionary.txt")); // Create a new BufferedReader, looking for dictionary.txt
List<String> lines = new ArrayList<String>(); // New ArrayList to keep track of the lines
String line; // Current line
Random rand = new Random(); // New random object
String word; // The computer's word
/********************* Start compWord *********************/
// Start reading the txt file
line = reader.readLine();
// WHILE the line isn't null
while(line != null)
{
// Add the line to lines list
lines.add(line);
// Go to the next line
line = reader.readLine();
}
// Set the computers word to a random word in the list
word = lines.get(rand.nextInt(lines.size()));
if(word.length() > MAX_COUNT)
compWord();
// Return the computer's word
return word;
}
据我了解,它应该只返回少于8个字符的单词? 知道我在做什么错吗? if语句应调用compWord,直到单词少于8个字符。 但是由于某种原因,我仍然能从10到15个字符中得到单词。
看这段代码:
if(word.length() > MAX_COUNT)
compWord();
return word;
如果选择的单词长于您的限制,则您将递归调用compWord
但忽略了返回值,反正只是返回了“太长”的单词。
就个人而言,我建议您避免递归,而只需使用do
/ while
循环即可:
String word;
do
{
word = lines.get(rand.nextInt(lines.size());
} while (word.length() > MAX_COUNT);
return word;
或者,当你读了前面行筛选:
while(line != null) {
if (line.length <= MAX_COUNT) {
lines.add(line);
}
line = reader.readLine();
}
return lines.get(rand.nextInt(lines.size()));
这样,您只需要挑选有效的行即可。
请注意,使用Files.readAllLines
是从文本文件中读取所有行的一种相当简单的方法-顺便说一句-当前您之后不会关闭文件...
如果单词长度超过8个字符,则只需再次调用方法,然后继续,就不会有任何变化。
所以:
您正在从文件中获取所有单词,
然后从列表中获得一个随机单词,并将其放入word
String中,
如果单词长度超过8个字符,则该方法将再次运行。
但是 ,最后,它将始终返回它首先选择的单词。 问题在于您只是递归地调用该方法,而对返回值却不执行任何操作。 您正在调用一个方法,它将执行某些操作,并且调用者方法将继续,在这种情况下,请返回您的word
。 此方法是否递归无关紧要。
相反,我建议您按照Skeet的建议使用非递归解决方案,或者对递归及其使用方法有所了解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.