代码不停止重复

时间:2014-04-01 02:53:18

标签: java printing

我有一个LinkedList(我必须使用LinkedList作为程序)我从文件中读取的单词。我从文件中读取了这些单词并将它们放在LinkedList中。然后我通过LinkedList来计算每个单词出现的次数,但我只想让每个单词以LinkedList中的次数打印一次。

for(int i2 = 0; i2 < b.size(); i2++)
    {
        word2 = b.get(i2);
        for(int j2 = 0; j2 < b.size(); j2++)
        {
            if(word2.equals(b.get(j2)))
            {
                counter++;
            }
        }
        for(int k2 = 0; k2 < wordList.size(); k2++)
        {
            if(word2.equals(k2))
            {
                found = true;
            }
        }
        if(found == false)
        {
            wordAndCount = word2 + " " + counter;
            wordList.push(wordAndCount);
        }

        counter = 0;
        found = false;
    }

此代码应该在它放入之前检查单词是否在第二个LinkedList中(因为我不想更改我的原始LinkedList),这样当我打印第二个LinkedList时,每个单词只打印一次。然而,它仍然每次打印每个单词(由于某种原因,它不会重复打印最后一个单词)。我怎么能阻止这个?

我可以完全更改代码,只要它只打印一次!

1 个答案:

答案 0 :(得分:0)

你将这个词与一个索引进行比较..这就是为什么它不起作用.. 试试这个:

for (int i2=0;i2<b.size();i2++)
{
    word2 = b.get(i2);
    for (int j2 = 0; j2 < b.size(); j2++)
    {
        if (word2.equals(b.get(j2)))
        {
            counter++;
        }
    }

    for (int k2 = 0; k2 < wordList.size(); k2++)
    {
        if(word2.equals(wordList.get(k2).split(" ")[0])) // <-- here..
        {
            found = true;
        }
    }

    if (found == false)
    {
        wordAndCount = word2 + " " + counter;
        wordList.push(wordAndCount);
    }

    counter = 0;
    found = false;
}

但这可能会更好:它会首先检查wordlist中单词是否存在,如果存在,则跳过进一步的过程(计算等等),并检查下一个单词..

OUTER:
for (int i2=0;i2<b.size();i2++)
{
    word2 = b.get(i2);
    for (int k2 = 0; k2 < wordList.size(); k2++)
    {
        if(word2.equals(wordList.get(k2).split(" ")[0])) // <-- here..
        {
            continue OUTER;
        }
    }

    for (int j2 = 0; j2 < b.size(); j2++)
    {
        if (word2.equals(b.get(j2)))
        {
            counter++;
        }
    }

    wordAndCount = word2 + " " + counter;
    wordList.push(wordAndCount);

    counter = 0;
}

其他建议:您可能希望查看此HashMap examples以获得更好的实施(使用keyvalue概念)..