简体   繁体   中英

How do to input values and strings into class object? Getting NullPointerException

I'm trying to add String name, long phoneNumber, and String comment to the Contact object, then place it into object array.

public class VectorOfContacts implements ProjTwo
{
    Contact[] contacts;
    public void addContact(Contact c)
    {

            if(isFull());
            incrementCapacity();
            size++;
            String name = "";
            long number = 0;
            String comment = "";
            c.setName(name);
            c.setPhoneNumber(number);
            c.setComment(comment);
            for (int i = 0; i < contacts.length; i++)
            {
                if (contacts[i] == null)
                {
                    contacts[i] = c;
                }
            }
            System.out.println("Added to input");

    }
}

However, I get a NullPointerException starting in c.setName(name).

You're not passing an instance of a Contact into the method. It's likely you're doing this:

Contact c;
...
addContact(c);

In this case, you're actually passing null into the addContact method. You need to something like this instead:

Contact c = new Contact();
...
addContact(c);

I'm assuming that the method 'setName' in Contact just does this:

public void setName(String name){
    this.name = name;
}

If that is the case, then c, must be null. This would mean that the problem is in the method which calls 'addContact(Contact c)'. Somehow, it is passing a null argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM