[英]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"));
創建長度為100
的Directory
數組時,它以100個null
引用開頭。 您已超過所有已填充的現有Directory
對象(如果有),並且在到達數組末尾之前已達到null
引用。
在訪問getName()
之前,測試directory[x]
是否為null
。 由您決定是立即對null
數組元素返回-1
還是繼續搜索數組。
directory[x].getName()
為空。 首先檢查它是否為null,然后執行.getName()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.