我正在进行测试任务,我必须从用户处获取姓名和电话号码并将其保存到arraylist。 我创建了三个类
以下是课程的内容:
的 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));
}
}
但是在执行主要课程时我遇到了错误。
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)
我验证了我在Mobilemain.java第19行传递的对象不为空
答案 0 :(得分:3)
MobilePhone为null,您必须首先初始化变量:
static MobilePhone mobilephone = new MobilePhone();
只有这样你才能使用addPhone