我在使用 Java 中的一个方法时遇到了问题,该方法抛出了一个错误:
Exception in thread "main" java.lang.NullPointerException
at FamilyTree$FamilyTreeNode.access$9(FamilyTree.java:5)
at FamilyTree.displayFamilyMember(FamilyTree.java:166)
at FamilyTreeTest.main(FamilyTreeTest.java:28)
有问题的方法是:
public void displayFamilyMember(){
boolean cascade = false;
int memberIdentifier;
displayFamily();
memberIdentifier = Input.getInteger("Input member ID");
currentNode = ancestor ;
if (currentNode.identifier == memberIdentifier || currentNode.partner.identifier == memberIdentifier){
cascade = true;
if(currentNode.partner!= null){
System.out.println(currentNode.Name + " ID[" + currentNode.identifier + "] Partner: " + currentNode.partner.Name + " ID[" + currentNode.partner.identifier + "]");
}else{
System.out.println(currentNode.Name + " ID[" + currentNode.identifier + "] has no partner");
}
}
if(currentNode.child != null){
currentNode = currentNode.child;
if (currentNode.identifier == memberIdentifier || cascade == true || currentNode.partner.identifier == memberIdentifier){
if(currentNode.partner!= null){
System.out.println(" " + currentNode.Name + " ID[" + currentNode.identifier + "] Partner: " + currentNode.partner.Name + " ID[" + currentNode.partner.identifier + "]");
}else{
System.out.println(" " + currentNode.Name + " ID[" + currentNode.identifier + "] has no partner");
}
}
}
if (currentNode.sibling!= null){
while(currentNode.sibling != null){
currentNode = currentNode.sibling;
if (currentNode.identifier == memberIdentifier || cascade == true || currentNode.partner.identifier == memberIdentifier){
System.out.println("Check for match performed, checking partner !- null");
if(currentNode.partner!= null){
System.out.println(" " + currentNode.Name + " ID[" + currentNode.identifier + "] Partner: " + currentNode.partner.Name + " ID[" + currentNode.partner.identifier + "]");
}else{
System.out.println(" " + currentNode.Name + " ID[" + currentNode.identifier + "] has no partner");
}
}
}
}
else{
System.out.println("member not found");
}
}
引发错误的行:
if (currentNode.identifier == memberIdentifier || cascade == true || currentNode.partner.identifier == memberIdentifier){
现在作为猜测,我会说我收到此错误,因为我正在检查其值的 currentNode.partner.identifier 为 null / currentNode.partner 节点不存在。
这不会阻止前两个相同的检查正常运行,所以我有点困惑为什么这条线有任何不同。
结构是
Alice[2] <--partner-- John[1]
|
Ted[3] --sibling--> Eric[4] --sibling--> Joanne[5]
编辑:感谢您的回复,我了解它现在是如何工作的。
if (currentNode.identifier == memberIdentifier || currentNode.partner.identifier == memberIdentifier){