题目
Account.java 账户类
public class Account {
//属性 余额
private double balance;//默认为0
//构造器
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("余额不足");
}
}
}
Bank.java 银行
public class Bank {
private Customer[] customers;// 存放多个客户的数组
private int numberOfCustomers;// 记录客户的个数
//构造器 给数组定义10个长度
public Bank() {
customers = new Customer[10];
}
// 添加客户
public void addCustomer(String f, String l) {
Customer cust = new Customer(f, l);
// customers[numberOfCustomers] = cust;
// numberOfCustomers++;
// 或
//customers[numberOfCustomers++]是空指针,现在被赋予了cust的地址值,,不是空指针了。
customers[numberOfCustomers++] = cust;
}
// 获取客户的个数
public int getNumOfCustomers() {
return numberOfCustomers;
}
// 获取指定位置上的客户
public Customer getCustomer(int index) {
// return customers[index];//可能报异常: 数组越界 空指针啥的
if (index >= 0 && index < numberOfCustomers) {
return customers[index];
}
//否则返回空
return null;
}
}
Customer.java 客户类
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;
}
//返回firstName
public String getFirstName() {
return firstName;
}
//返回lastName
public String getLastName() {
return lastName;
}
}
BankTest.java 银行测试类
public class BankTest {
public static void main(String[] args) {
Bank bank = new Bank();
bank.addCustomer("Jane", "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("万里", "杨");
System.out.println("银行客户的个数为:" + bank.getNumOfCustomers());
}
}