直接附上代码
Account类
package com.luokai.exer2;
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) {
this.balance += amt;
System.out.println("存款成功,您成功存入¥" + amt);
}
//取款
public void withdraw(double amt) {
if(balance >= amt) {
this.balance -= amt;
System.out.println("取款成功,您成功取出¥" + amt);
}
else {
System.out.println("取款失败,您的账户余额不足!");
}
}
}
Customer类
package com.luokai.exer2;
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 String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
}
Bank类
package com.luokai.exer2;
public class Bank {
//属性
private Customer[] customers;//存放对个客户的数组
// private Customer[] customers = new Customer[10];//两种方式创建一个长度为10的数组
private int numberOfCustomer;//记录客户的个数
//构造器
public Bank() {
customers = new Customer[10];
}
//方法
//添加客户
public void addCustomer(String f,String l) {
Customer cust = new Customer(f,l);
// customers[numberOfCustomer] = cust;
// numberOfCustomer ++;
customers[numberOfCustomer ++] = cust;
}
//获取客户的个数
public int getNumberOfCustomer() {
return numberOfCustomer;
}
//获取指定位置上的客户
public Customer getCustomer(int index) {
// return customers[index];//肯报异常
if(index >= 0 && index < numberOfCustomer) {
return customers[index];
}
return null;
}
}
BankTest类
package com.luokai.exer2;
public class BankTest {
public static void main(String[] args) {
Bank bank = new Bank();
bank.addCustomer("Tom", "Smith");
bank.getCustomer(0).setAccount(new Account(2000));
bank.getCustomer(0).getAccount().withdraw(200);
double balance = bank.getCustomer(0).getAccount().getBalance();
System.out.println("客户 " + bank.getCustomer(0).getFirstName() +
" 的账户余额为" + balance);
System.out.println("**********************");
bank.addCustomer("Jane", "Smith");
bank.getCustomer(1).setAccount(new Account(3000));
bank.getCustomer(1).getAccount().deposit(500);
double balance1 = bank.getCustomer(1).getAccount().getBalance();
System.out.println("客户 " + bank.getCustomer(1).getFirstName() +
" 的账户余额为" + balance1);
}
}