簡體   English   中英

方法在應返回-1時返回NullPointerException

[英]Method returning a NullPointerException when it should be returning a -1

只要我輸入的名稱在目錄中,以下代碼即可正常運行。 如果該名稱在目錄中不存在,則返回NullPointerException。 如果目錄中不存在該名稱,我不理解cos,它應該只返回-1。 為什么例外? 感謝您的指導。

public  class  Direct{
    //Directory is a class that contain a name and get/set methods for it.
    private Directory[] directory = new Directory[100];

        public int find(String name){
            for (int x=0; x < directory.length; x++){
                if (directory[x].getName().equals(name)){ //exception refers to this line to hold the error
                    return x;
                }
            }
            return -1;
        }
}



//Testing on main method

Direct direct = new Direct();

//This works cos the name John is in the directory.
System.out.println(direct.find("John"));

This returns an error cos x is not present in the directory.
System.out.println(direct.find("x"));

創建長度為100Directory數組時,它以100個null引用開頭。 您已超過所有已填充的現有Directory對象(如果有),並且在到達數組末尾之前已達到null引用。

在訪問getName()之前,測試directory[x]是否為null 由您決定是立即對null數組元素返回-1還是繼續搜索數組。

directory[x].getName()為空。 首先檢查它是否為null,然后執行.getName()

暫無
暫無

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

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