簡體   English   中英

二進制搜索樹,搜索方法

[英]Binary Search Tree, Search method

我試圖運行我的Binary Search Tree ,我正在主程序中創建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;
                }

您能否檢查temp.search(choice2)是否返回非空值? 使用空引用進行強制轉換會導致此類錯誤

除此之外,請確保您為BinaryNode a執行的強制轉換確實是Employee。 (盡管這與NullPointerException無關)

您的search方法可以返回null ,因此您應該重新組織代碼並添加Employee newEmp = (Employee) a.obj; else條件的一部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM