1.为银行数据库设计一个类。数据库应支持以下操作:
将一定金额存入账户
从账户中提取一定金额
返回指定帐户中的金额(即余额)的值
将金额从一个帐户转移到另一个帐户
- 编写一个应用程序类银行帐户应用程序来测试银行帐户,
即创建多个实例并调用BankAccount的每个方法。
1.为银行数据库设计一个类。数据库应支持以下操作:
将一定金额存入账户
从账户中提取一定金额
返回指定帐户中的金额(即余额)的值
将金额从一个帐户转移到另一个帐户
即创建多个实例并调用BankAccount的每个方法。
1、操作类:BankAccount类
package cn.bdqn.demo02;
public class BankAccount {
// 定义账户、余额属性
private String cardId;
private int balance;
// 添加无参构造
public BankAccount() {
}
// 添加有参构造
public BankAccount(String cardId, int balance) {
this.cardId = cardId;
this.balance = balance;
}
// 添加get/set方法
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
// 存款:将一定金额存入账户
public void deposit(int money) {
int balance = this.balance;
this.balance = balance + money;
System.out.println("存款成功,当前账户余额为" + this.balance + "元");
}
// 取款:实现从账户中提取一定金额的功能
public void withdraw(int money) {
int balance = this.balance;
if (balance >= money) {
this.balance = balance - money;
System.out.println("取款成功,当前账户余额为" + this.balance + "元");
} else if (balance < money) {
System.out.println("取款失败,您的余额不足");
}
}
// 转账:实现将金额从一个帐户转移到另一个帐户的功能
public void transfer(BankAccount bankAccount) {
if (balance > 0) {
this.balance = bankAccount.getBalance() + this.balance;
bankAccount.setBalance(0);
System.out.println("转账成功,"+this.getCardId()+"余额为" + this.balance + "元");
System.out.println("转账成功,"+bankAccount.getCardId()+"余额为" + bankAccount.getBalance() + "元");
} else {
System.out.println("转账失败,您的余额不足");
}
}
}
2、测试类:BankTest类
package cn.bdqn.demo02;
public class BankTest {
public static void main(String[] args) {
//初始化两张银行卡卡号和余额
BankAccount account1 = new BankAccount("6227****3301", 1000);
BankAccount account2 = new BankAccount("6227****2533", 2000);
//向account1银行卡存入500
account1.deposit(500);
//从account2银行卡取出800
account2.withdraw(800);
//将account1银行卡的钱转账到account2银行卡中
account2.transfer(account1);
}
}
3、效果: