java - Why my program is failing with null pointer exception -
this question has answer here:
- what nullpointerexception, , how fix it? 12 answers
i working on test assignment have take name , phone number user ans save them arraylist. created 3 classes
- contacts: store contact details.
- mobilephone: store contacts objects.
- mobilemain : begins program execution.
following content of 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 main class getting below error.
enter name: fgsdg enter phone number 234234 exception in thread "main" java.lang.nullpointerexception @ mobilephone.mobilemain.addcontact(mobilemain.java:19) @ mobilephone.mobilemain.main(mobilemain.java:10)
i verified object passing @ line 19 in mobilemain.java not null
mobilephone null, have initialize variable first:
static mobilephone mobilephone = new mobilephone();
only can use addphone
Comments
Post a Comment