首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

我正在尝试在一个简单的银行系统上实现和‘撤销’JButton,它将撤销上一次执行的操作

在一个简单的银行系统中实现和撤销JButton,可以通过以下步骤来完成:

  1. 首先,需要定义一个数据结构来存储用户的操作历史,以便实现撤销功能。可以使用一个栈(Stack)数据结构来保存每次操作的信息。
  2. 当用户执行一个操作时,将该操作的相关信息(如操作类型、操作金额等)压入栈中。
  3. 当用户点击撤销按钮时,从栈中弹出最近一次的操作信息,并根据该信息执行相反的操作。例如,如果最近一次操作是存款,那么执行撤销操作时就是取款;如果最近一次操作是取款,那么执行撤销操作时就是存款。
  4. 在执行撤销操作后,需要更新用户的账户余额和操作历史。

以下是一个简单的示例代码:

代码语言:txt
复制
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;
    }
}

这个示例代码实现了一个简单的银行系统,其中包含了存款、取款和撤销操作。每次操作都会将相关信息压入栈中,撤销操作会从栈中弹出最近一次的操作信息,并根据操作类型执行相反的操作。通过调用depositwithdraw方法来进行存款和取款操作,调用undo方法来执行撤销操作。

请注意,这只是一个简单的示例,实际的银行系统可能需要更复杂的逻辑和功能。在实际开发中,还需要考虑并发访问、数据持久化、安全性等方面的问题。

推荐的腾讯云相关产品:腾讯云服务器(CVM)和腾讯云数据库(TencentDB)。腾讯云服务器提供可靠、安全、高性能的云服务器实例,可满足各种规模的应用需求;腾讯云数据库提供高可用、可扩展的数据库服务,支持多种数据库引擎和存储引擎。

腾讯云服务器(CVM)产品介绍链接:https://cloud.tencent.com/product/cvm 腾讯云数据库(TencentDB)产品介绍链接:https://cloud.tencent.com/product/cdb

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券