我正在致力于实现一个花卉链接列表。我已经成功地让程序做我想做的事。我可以显示列表的内容、每个节点对象的属性,并且可以对列表执行其他操作。但是,如果我只想显示每个对象的唯一出现次数和计数,该怎么办?
例如,假设我将 2 个 Rose 对象和 1 个 Daffodil 对象添加到列表中。如果我使用当前方法显示内容,它将在控制台中将每个对象显示在其自己的行上。但我想开发一种新的查找方法,显示类似以下内容:
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 if 中添加第二个条件。它是:
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;
}
关于Java 对象链表。我怎样才能统计每个独特的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24967740/