簡體   English   中英

為什么我的單詞不少於8個字符?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM