Java 未正确生成链接列表输出

Java 未正确生成链接列表输出,java,linked-list,Java,Linked List,堆垛机 我是这个网站的新手,我认为就一个涉及打印链接列表的正确输出的特定问题来这里寻求帮助是明智的。 其想法是采用一个程序,该程序使用数组生成一个列表,并将其转换为一个链表,同时获得相同的结果。现在,我已经做了几个小时了,尽管我已经到了输出被实际打印的地步(最后),但并没有得到所需的结果 要求结果: 注意:此结果是使用数组生成的 单词:此计数:2 单词:课程数:2 单词:检查计数:1 单词:计数:7 字:构造计数:1 单词数:9 单词:算法计数:4 单词:和计数:9 我获得的结果: 注意:此

堆垛机

我是这个网站的新手,我认为就一个涉及打印链接列表的正确输出的特定问题来这里寻求帮助是明智的。 其想法是采用一个程序,该程序使用数组生成一个列表,并将其转换为一个链表,同时获得相同的结果。现在,我已经做了几个小时了,尽管我已经到了输出被实际打印的地步(最后),但并没有得到所需的结果

要求结果:
注意:此结果是使用数组生成的
单词:此计数:2
单词:课程数:2
单词:检查计数:1
单词:计数:7
字:构造计数:1
单词数:9
单词:算法计数:4
单词:和计数:9


我获得的结果:
注意:此结果是在将数组方法转换为链表时生成的

单词:信念计数:2
单词:我的计数:2
字数:个数:2
单词:最佳计数:2
单词:计数:2
单词数:2
单词:are count:2
单词:事实计数:2
单词:计数:2

我不太清楚为什么会这样,我似乎无法追踪它。我试着翻阅我的笔记并搜索,但没有结果。我不确定它是否与setNext(…)[节点类的一部分]有关,或者我在哪里调用incrementCount()方法[Word类的一部分]。我甚至不相信setNext(…)有什么目的,但它只是代码的一部分,在这一点上什么也不做

我希望我的交付没有偏离轨道,并且可以为我的尝试提供解决方案。我知道我已经达到了极限,因为我想不出任何其他与此相关的东西

期待您的建议

谢谢

T3


我可以马上看到一些问题:

  • 除非
    getWord()
    方法做了一些非常奇怪的事情,否则只有当第一个单词与新添加的单词匹配时,它才会增加计数
  • 无论是否存在匹配项,您都将向列表的标题添加一个新的
    节点
    ,再加上第一个问题,所有问题的计数都将为2
  • printList()
    中,您需要从
    top
    开始,而不是
    top.getNext()

getWord()仅返回存储在节点中的word对象。这就是它的全部功能。我试图修复printList()方法,但仍然无法解决错误。您是否理解我所说的每次调用
addWord()
时总是添加
节点的内容?去掉那一行,试着重复你的匹配列表,而不是仅仅检查
顶部的内容
我很感谢你的帮助,但鉴于我没有进步,我将向你表示感谢,并让问题保持原样。:-)我尽了最大的努力。很荣幸收到你的答复。
private Node top;

public WordList()
{
   top = null;
}

    // This method adds words to the linked list.
public void addWord( String w )
{       
   Word word = new Word( w );
   top = new Node(word,top);

       // Checks to see if a particular word is present more than once.
       // If the particular word is encountered more than once, it 
       // increments the word count for that particular word, else
       // a new node is created to store another word. The word check
       // process is repeated once more.
       // Note: getWord() is part of the Node class that attempts to retrieve
       // a word that is held in a particular node.
       // matchesWord(...) determines whether a particular word (string) has been 
       // encountered. If result is true, the number of times
       // the word is encountered should be incremented. 
   if( top.getWord().matchesWord( w ))
   {
      top.getWord().incrementCount();
   }
   else
   {
      Word newWord = new Word ( w );
      Node newNode = new Node(newWord, top);    
      //top = newNode;
      top.setNext(newNode);
   }
} // end addWord

    // This method prints out the linked list.
public void printList()
{
    Node currentNode;

    currentNode = top.getNext();
    while(currentNode != null)
    {
        System.out.println(currentNode.getWord());
        currentNode = currentNode.getNext();
    }
}