public void showAll(){//to string method
for (int i=0;i<phoneBook.length;i++){//index is going till 2 where it
System.out.println(phoneBook[i].toString());
}
//the above code iterates for 20 times because the length of the array is 20.
public phoneBookUnsoterdOptimizedArray( )
{
next = 0;
size = 20;//this initializes the array to size 20.
phoneBook = new PhoneBook[size];
}//end of constructor
我尝试使用 if
语句检查 null
,但这不起作用。
输出
Phone Number: 4695866399
lastName: Ayoub
First Name: Rehan
address: 9323 Amberton Pkwy
Exception in thread "main" Phone Number: 971506236329
lastName: Ayoub
First Name: Syed
address: 14th Street Nyadat
java.lang.NullPointerException
at phonebook.phoneBookUnsoterdOptimizedArray.showAll(phoneBookUnsoterdOptimizedArray.java:74)
at phonebook.FA2015PROJECT_Ayoub.main(FA2015PROJECT_Ayoub.java:35)
最佳答案
您可以显式检查 null
:
for (int i = 0; i < phoneBook.length; i++) {
if (phoneBook[i] == null) {
break;
}
System.out.println(phoneBook[i].toString());
}
关于java - 数组长度 20 但我希望它在读取最后一个节点后就中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33764780/