我是java新手,我在编译器上遇到此错误
在线程" main"中输入名称:pot异常 java.lang.NullPointerException at account.BankTest.main(BankTest.java:17)C:\ Users \ Carl the INVOKER \应用程序数据\本地\ NetBeans的\缓存\ 8.2 \执行-片段\ run.xml:53: Java返回:1 BUILD FAILED(总时间:7秒)
班级帐户
package account;
public class Account {
private String name;
private String surname;
private int age;
private int sex;
public Account(String name, String surname, int age, int sex) {
this.name = name;
this.surname = surname;
this.age = age;
this.sex = sex;
}
public Account() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
}
Class BankTest
package account;
import java.util.Scanner;
public class BankTest {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
Account user[] = new Account[10];
System.out.println("Enter name : ");
user[1].setName(scan.nextLine());
System.out.println(user[1].getName());
}
}
答案 0 :(得分:0)
您的数组中没有值。 Account user[] = new Account[10];
仅创建数组,但不初始化数组中的元素。因此,当您执行此语句user[1].setName(scan.nextLine());
时,user[1]
不引用Account对象,它实际引用null
值;因此,调用方法setName
将抛出NullPointerException。要初始化您的帐户数组,您需要在访问它之前执行此类操作。
for (int i=0: i<user.length; i++) {
user[i] = new Account(null, null, 0, 0);
}