-2

I am working on a test assignment where i have to take name and phone number from the user ans save them to the arraylist. I created three classes

  • Contacts: to store contact details.
  • MobilePhone: to store the contacts objects.
  • Mobilemain : begins program execution.

Following is the content of the classes:


Contacts.java

    package mobilephone;

    public class Contacts {
    private int number;
    private String name;

    public Contacts(String name,int number ) {
        this.name = name;
        this.number = number;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

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

}

MobilePhone.java

package mobilephone;

import java.util.ArrayList;

public class MobilePhone {
    private ArrayList<Contacts> phonebook = new ArrayList<Contacts>();

    public void addPhone(Contacts contact) {
        phonebook.add(contact);
    }

    public void showContacts(){
        for(int i=0 ;i< phonebook.size();i++){
        System.out.println(phonebook.get(i).getName()+" => "+phonebook.get(i).getNumber());
        }
    }


}

Mobilemain.java

package mobilephone;

import java.util.Scanner;

public class Mobilemain {
    static Scanner scanner = new Scanner(System.in);
    static Contacts contacts;
    static MobilePhone mobilephone;
    public static void main(String[] args){
        addContact();       
        mobilephone.showContacts();
    }

    static void addContact(){
        System.out.print("Enter name: ");
        String name= scanner.nextLine();
        System.out.println("Enter phone number");
        int number= scanner.nextInt();
        mobilephone.addPhone(new Contacts(name,number));

    }


}

But on executing the main class i am getting below error.

Enter name: fgsdg
Enter phone number
234234
Exception in thread "main" java.lang.NullPointerException
    at mobilephone.Mobilemain.addContact(Mobilemain.java:19)
    at mobilephone.Mobilemain.main(Mobilemain.java:10)

I verified that the object i am passing at line 19 in Mobilemain.java is not null

thinkingmonster
  • 5,063
  • 8
  • 35
  • 57

1 Answers1

3

MobilePhone is null, you have to initialize the variable first:

static MobilePhone mobilephone = new MobilePhone();

Only then you can use the addPhone

AxelH
  • 14,325
  • 2
  • 25
  • 55
Diogo Rosa
  • 756
  • 1
  • 5
  • 24