0

I keep getting a null pointer exception at run time.

public class MobilePhone {
ArrayList<Contacts> contactsArray;
private String myNumber;

public MobilePhone(ArrayList<Contacts> contactsArray, String myNumber) {
    super();
    this.contactsArray = new ArrayList<Contacts>();
    this.myNumber = myNumber;
}
public MobilePhone(){

}


public void addContact(Contacts contact) {
    //contactsArray.contains(name);

    contactsArray.add(contact);
}

I have the addContact method take a Contacts object to add to the arraylist and i call that method in the createContact method in the demo class below, where i also create the object and set the arguments. Ive tried it a couple of different ways, but the object ends up never being created.

public class challengeDemo {
static MobilePhone phone = new MobilePhone();
static Scanner input = new Scanner(System.in);
public static void main(String[]args){

    createContact();
    //System.out.println(phone.contactsArray.get(0));

}

public static void createContact(){
    System.out.println("Enter Name: ");
    String userName = input.next();
    System.out.println("Enter Number: ");
    String userNumber = input.next();

    phone.addContact(new Contacts(userName,userNumber));

}
 }
 }

I also have a contacts constructor.

public class Contacts {
private String name;
private String phoneNumber;

public Contacts(String name,String phoneNumber){
    this.name = name;
    this.phoneNumber = phoneNumber;
}
Aaronbob49
  • 33
  • 1
  • 5
  • You're calling the wrong constructor. – shmosel Oct 10 '17 at 21:01
  • i also have a contacts constructor, i was thinking ihad to create the contact object with that constructor. which one should i use? – Aaronbob49 Oct 10 '17 at 21:05
  • In this case, the zero-argument constructor does not initialise the fields `contactsArray` or `myNumber`, so when you all `addContact` you throw the `NullPointerException`. Also, your other constructor ignores the `contactsArray` parameter it is passed, and instead creates a new `ArrayList` – SteveR Oct 10 '17 at 21:07
  • Use the first `MobilePhone` constructor - the one that initializes `contactsArray`. Or just initialize it separately. – shmosel Oct 10 '17 at 21:07

0 Answers0