我正在尝试运行我的二叉搜索树
,我正在主程序中创建Employee
类型的对象,这似乎不会给我带来问题,但是当我选择在我的 BST
中搜索项目,程序终止。
System.out.println("Searching the Binary Search Tree");
System.out.println("Enter surname to search for:");
String choice2 = sc.nextLine();
BinaryNode a = temp.search(choice2);
Employee newEmp = (Employee) a.obj;
if (a == null)
{
System.out.println("Not Found");
}
else
{
System.out.println(newEmp.getData());
}
break;
}
当程序终止时,它指向该行
Employee newEmp = (Employee) a.obj;
给出的错误是,java.lang.NullPointerException: null
谁能告诉我为什么会发生这种情况?
最佳答案
您无法访问空对象的.obj。 检查是否a==null后应移动行。
System.out.println("Searching the Binary Search Tree");
System.out.println("Enter surname to search for:");
String choice2 = sc.nextLine();
BinaryNode a = temp.search(choice2);
if (a == null)
{
System.out.println("Not Found");
}
else
{
Employee newEmp = (Employee) a.obj;
System.out.println(newEmp.getData());
}
break;
}
关于java - 二叉搜索树,搜索方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14353922/