Account类:
public class Account {
private double balance;
public Account(double init_balance) {
this.balance = init_balance;
}
public double getBalance() {
return balance;
}
public void deposit(double amt) {
if(amt > 0) {
balance += amt;
System.out.println("存钱成功");
}
}//存钱
public void withdraw(double amt) {
if(balance >= amt) {
balance -= amt;
System.out.println("取钱成功");
}else {
System.out.println("余额不足");
}
}//取钱
}
Customer类:
public class Customer {
private String firstName;
private String lastName;
private Account account;
public Customer(String f,String l) {
this.firstName = f;
this.lastName = l;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
}
Bank类:
public class Bank {
private Customer[] customers;//存放多个客户的数组
private int numberOfCustomers;//记录客户的个数
public Bank() {
customers = new Customer[10];//进行初始化,如果数组里是null,则无法进行赋值
}
//添加客户
public void addCustomer(String f,String l) {
Customer cust = new Customer(f,l);
// customers[numberOfCustomers] = cust;
// numberOfCustomers++;
customers[numberOfCustomers++] = cust;//合并成一个
}
//获取客户的个数
public int getNumCustomers() {
return numberOfCustomers;
}
//获得指定位置上的客户
public Customer getCustomer(int index) {
// return customers[index];//可能报异常
if(index >= 0 && index < numberOfCustomers) {
return customers[index];
}
return null;
}
}
BankTest:
public class BankTest {
public static void main(String[] args) {
Bank bank = new Bank();
bank.addCustomer("Janc", "Smith");
//连续操作
bank.getCustomer(0).setAccount(new Account(2000));
bank.getCustomer(0).getAccount().withdraw(500);
double balance = bank.getCustomer(0).getAccount().getBalance();
System.out.println("客户:" + bank.getCustomer(0).getFirstName() + ",账户余额为:" + balance);
System.out.println("*********************************************");
bank.addCustomer("mis", "cheng");
System.out.println("银行客户的个数为:" + bank.getNumCustomers());
}
}
输出:
取钱成功
客户:Janc,账户余额为:1500.0
*********************************************
银行客户的个数为:2