繁体   English   中英

Java链接的对象列表。 如何记录每个唯一的对象?

[英]Java Linked List of Objects. How can I keep count of each unique object?

我当时正在实施花朵的链接清单。 我已经成功地使程序执行了我想做的事情。 我可以显示列表的内容,每个节点对象的属性,还可以对列表做其他事情。 但是,如果我只想显示每个对象的唯一出现次数和计数怎么办?

例如,假设我将2个Rose对象和1个Daffodil对象添加到列表中。 如果使用当前方法显示内容,则它将在控制台中的每个行上显示每个对象。 但是我想开发一种新的find方法,该方法显示如下内容:

There are  2 occurrences of Rose!
There are 1 occurrences of Daffodil!

用我当前的代码,这将无法工作。 我得到:

There is a Rose!
There is a Rose!
There is a Daffodil!

这是到目前为止我一直在尝试的实验性find2方法:

public void find2(String searchName){
    Node theNode = firstNode;
    int occurrences = 0;

    if(!isEmpty()){
        while (theNode.getItem().getName() != searchName){
            if (theNode.getItem().getName().equals(searchName)){
                occurrences++;
            }
            else if (theNode.getNext() == null){
                System.out.println("Flower not found!");
                return;
            }

            theNode = theNode.getNext();

        }

        System.out.println("Found " + occurrences + " occurrences of " + searchName + ".");
    }
}

逻辑有问题吗? 我已经尝试在else中添加第二个条件。 它是:

else if (theNode.getNext() == null && occurrences == 0){
    System.out.println("Flower not found!");
    return null;
}

但是,那也没有帮助。 运行该程序时会发生的事情是,根据我对方法的修改方式,我将输入要搜索的名称并将其停滞-换句话说,控制台使我可以输入更多内容,但它没有任何作用。 否则会给我以下错误:

Exception in thread "main" java.lang.NullPointerException
    at LinkedList.find2(LinkedList.java:69)
    at FinalProject.searchFlowers(FinalProject.java:81)
    at FinalProject.<init>(FinalProject.java:37)
    at FinalProject.main(FinalProject.java:10)

如果您想查看所有代码,我可以提供。 我感谢任何提示或建议! 非常感谢您的宝贵时间。

在测试是否相等之前,首先测试null!

while (theNode.getItem().getName() != searchName) { // <-- NO!
  if (theNode.getItem().getName().equals(searchName)) { // <-- B
    occurrences++;
  } else if (theNode.getNext() == null){ // <-- A
    System.out.println("Flower not found!");
    return;
  }
  theNode = theNode.getNext();
}

我相信你想要这样的东西

while (theNode != null) { // <-- null test.
  if (theNode.getItem().getName().equals(searchName)){ // <-- B
    occurrences++;
  } else { //theNode.getItem().getName() != searchName
    break;
  }
  theNode = theNode.getNext();
}
if (occurrences == 0) { // <-- A
  System.out.println("Flower not found!");
  return;
}

尝试这个

         while(theNode.getNext()!=null)
          {
            if(theNode.getNext().getName().equals(searchName))
            {
               occurrences++;
            }
         }
         if(occurences==0)
          { 
            System.out.println("Flower not Found");
          }
         else
          {
            System.out.println("Found items "+seachname+""+occurences);
          }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM