当我尝试在我的银行帐户计划中创建新客户时,我收到此例外:
Exception in thread "main" java.lang.NullPointerException
at bank.program.Customer.addAccount(Customer.java:18)
at bank.program.BankProgram.main(BankProgram.java:24)
Java Result: 1
这是什么意思,我需要改变什么才能摆脱它?
Bank
上课:
public class Bank {
String bankName;
private ArrayList<Customer> customers = new ArrayList<Customer>();
Bank(String bankName) {
this.bankName = bankName;
}
public void addCustomer(Customer newCustomer) {
customers.add(newCustomer);
}
}
Account
上课:
public abstract class Account {
protected double balance = 0;
protected String accountId;
public Account() {} //Defaultkonstruktor
public Account(double bal, String id) { //Konstruktor
if (balance >= 0) {
balance = bal;
}
else {
balance = 0;
}
accountId = id;
}
public abstract void deposit(double amount);
public abstract void withdraw(double amount);
public abstract double getBalance();
public abstract String getAccountId();
public void transfer(double amount, Account account) {
account.deposit(amount);
balance -= amount;
}
}
SavingsAccount
上课:
public class SavingsAccount extends Account {
private double interest = 2.9;
public SavingsAccount() {
super();
}
public SavingsAccount(double bal, String id) {
super(bal, id);
}
@Override
public void deposit(double amount) {
}
@Override
public void withdraw(double amount) {
}
@Override
public double getBalance() {
}
@Override
public String getAccountId() {
}
}
Customer
上课:
public class Customer {
private String firstName;
private String lastName;
private String number;
private ArrayList<Account> accounts;
Customer(String firstName, String lastName, String number) {
this.firstName = firstName;
this.lastName = lastName;
this.number = number;
}
public void addAccount(SavingsAccount account) {
accounts.add(account);
}
public ArrayList<Account> getAccounts() {
return accounts;
}
}
银行计划类:
public class BankProgram {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numberOfCustomers = 0;
Bank bank = new Bank("Bank name");
System.out.print("Enter amount to deposit: ");
double amount = input.nextDouble();
System.out.println("Account number: " + numberOfCustomers);
System.out.print("First name: ");
String firstName = input.next();
System.out.print("Last name: ");
String lastName = input.next();
System.out.print("Customer number: ");
String pnumber = input.next();
Customer newCustomer = new Customer(firstName, lastName, pnumber);
SavingsAccount savingsAccount = new SavingsAccount(amount, "11");
newCustomer.addAccount(savingsAccount);
bank.addCustomer(newCustomer);
}
}
答案 0 :(得分:5)
您尝试在不初始化存储它们的ArrayList
的情况下添加帐户。将其添加到Customer
构造函数中。
this.accounts = new ArrayList<Account>();
答案 1 :(得分:1)
在您的Customer类中,您声明ArrayList accounts
。然后,您有一个名为addAccount
的方法,但好像从未初始化此accounts
。
在您创建Customer
对象的地方,您需要说:
newCustomer.accounts = new ArrayList<Account>();