This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                在8个月前关闭。
            
        

我有3个类,Main,Contacts和ContactsManager。我的“ searchContact”方法出现以下错误。我不知道该如何解决。我正在遍历由“ friendsCount变量”表示的多个联系人的联系人索引数组。请帮助我修复searchContact方法。谢谢。

ContactsManager类

public class ContactsManager {

    // Fields
    Contact [] myFriends;
    int friendsCount;

    // Constructor
    ContactsManager() {
        this.friendsCount = 0;
        this.myFriends = new Contact[500];
    }

    // Methods
    void addContact(Contact contact) {
        myFriends[friendsCount] = contact;
        friendsCount++;
    }

    Contact searchContact(String searchName) {
        for(int i = 0; i < friendsCount; i++) {
            if(myFriends[i].name.equals((searchName))) {
                return myFriends[i];
            }
        }
        return  null;
    }
}


通讯录类

public class Contact {

    String name;
    String email;
    String phoneNumber;

}


主班

public class Main {

    public static void main(String[] args) {
        ContactsManager myContactManager = new ContactsManager();

        Contact con1 = new Contact();
        con1.name = "Albert";
        con1.phoneNumber = "9545899977";

        myContactManager.addContact(con1);

        Contact con2 = new Contact();
        con1.name = "Jason";
        con1.phoneNumber = "9545899944";

        Contact con3 = new Contact();
        con1.name = "Larry";
        con1.phoneNumber = "9545899911";

        Contact con4 = new Contact();
        con1.name = "Mary";
        con1.phoneNumber = "9545899933";

        Contact con5 = new Contact();
        con1.name = "Saraht";
        con1.phoneNumber = "9545899900";

        myContactManager.addContact(con2);
        myContactManager.addContact(con3);
        myContactManager.addContact(con4);
        myContactManager.addContact(con5);

        System.out.println(myContactManager.searchContact("Jason"));
    }
}

最佳答案

您总是在设置con1的值。

您的main方法实例化oth(con2,con3和con4),但未将其名称设置为任何值(因此为null)。主要方法必须更改如下。

    ContactsManager myContactManager = new ContactsManager();

    Contact con1 = new Contact();
    con1.name = "Albert";
    con1.phoneNumber = "9545899977";

    myContactManager.addContact(con1);

    Contact con2 = new Contact();
    con2.name = "Jason";
    con2.phoneNumber = "9545899944";


等等。

另外,在您的searchContact方法中,考虑如果找不到联系人(返回null)会发生什么情况。相反,请考虑抛出一个未找到的自定义异常,或者,而不是直接返回Contact,而是返回Optional(因为搜索可能找不到任何东西)。

08-06 21:24