数组长度为20但我希望它在读取最后一个节点后中断

时间:2015-11-17 18:51:07

标签: java arrays nullpointerexception

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)

2 个答案:

答案 0 :(得分:1)

您可以明确检查null s:

for (int i = 0; i < phoneBook.length; i++) {
    if (phoneBook[i] == null) {
        break;
    }
    System.out.println(phoneBook[i].toString());
 }

答案 1 :(得分:1)

此处发布的其他答案将解决您的问题,但这是另一种选择。

如果您计划break离开循环只是为了避免NullPointerException,您可以选择使用

String.valueOf(phoneBook[i])

而不是

phoneBook[i].toString()