在一个简单的银行系统中实现和撤销JButton,可以通过以下步骤来完成:
以下是一个简单的示例代码:
import java.util.Stack;
public class BankSystem {
private double balance;
private Stack<Operation> history;
public BankSystem() {
balance = 0.0;
history = new Stack<>();
}
public void deposit(double amount) {
balance += amount;
history.push(new Operation(OperationType.DEPOSIT, amount));
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
history.push(new Operation(OperationType.WITHDRAW, amount));
} else {
System.out.println("Insufficient balance.");
}
}
public void undo() {
if (!history.isEmpty()) {
Operation lastOperation = history.pop();
if (lastOperation.getType() == OperationType.DEPOSIT) {
balance -= lastOperation.getAmount();
} else if (lastOperation.getType() == OperationType.WITHDRAW) {
balance += lastOperation.getAmount();
}
} else {
System.out.println("No operations to undo.");
}
}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
BankSystem bank = new BankSystem();
bank.deposit(100.0);
System.out.println("Balance: " + bank.getBalance());
bank.withdraw(50.0);
System.out.println("Balance: " + bank.getBalance());
bank.undo();
System.out.println("Balance: " + bank.getBalance());
}
}
enum OperationType {
DEPOSIT,
WITHDRAW
}
class Operation {
private OperationType type;
private double amount;
public Operation(OperationType type, double amount) {
this.type = type;
this.amount = amount;
}
public OperationType getType() {
return type;
}
public double getAmount() {
return amount;
}
}
这个示例代码实现了一个简单的银行系统,其中包含了存款、取款和撤销操作。每次操作都会将相关信息压入栈中,撤销操作会从栈中弹出最近一次的操作信息,并根据操作类型执行相反的操作。通过调用deposit
和withdraw
方法来进行存款和取款操作,调用undo
方法来执行撤销操作。
请注意,这只是一个简单的示例,实际的银行系统可能需要更复杂的逻辑和功能。在实际开发中,还需要考虑并发访问、数据持久化、安全性等方面的问题。
推荐的腾讯云相关产品:腾讯云服务器(CVM)和腾讯云数据库(TencentDB)。腾讯云服务器提供可靠、安全、高性能的云服务器实例,可满足各种规模的应用需求;腾讯云数据库提供高可用、可扩展的数据库服务,支持多种数据库引擎和存储引擎。
腾讯云服务器(CVM)产品介绍链接:https://cloud.tencent.com/product/cvm 腾讯云数据库(TencentDB)产品介绍链接:https://cloud.tencent.com/product/cdb
领取专属 10元无门槛券
手把手带您无忧上云