1 個解答

評分
  • 7 年前
    最佳解答

    請參考我的做法

    import java.text.*;

    import java.util.*;

    class CKAccount {

    String ID, name;

    float balance;

    static int x = 1;

    ArrayList<Transaction> ts = new ArrayList<Transaction>();

    protected class Transaction {

    Date dt;

    final static int TYPE_CREATE = 0, TYPE_DEPOSIT = 1, TYPE_WITHDRAW = 2;

    final String[] typeString = {"CREATE", "DEPOSIT", "WITHDRAW"};

    int type;

    float amount, balance;

    Transaction(int type, float a, float b) {

    dt = Calendar.getInstance().getTime();

    this.type = type;

    amount = a;

    switch (type) {

    case TYPE_CREATE:

    balance = a;

    break;

    case TYPE_DEPOSIT:

    balance = a + b;

    break;

    case TYPE_WITHDRAW:

    balance = b - a;

    break;

    }

    }

    public String toString() {

    DateFormat df = DateFormat.getInstance();

    return df.format(dt) + " " + typeString[type] + " " + amount + " " +

    balance;

    }

    }

    CKAccount(String n, float f) {

    name = n;

    ID = "101" + String.format("%07d", x++);

    Transaction t = new Transaction(Transaction.TYPE_CREATE, f, balance);

    balance = t.balance;

    ts.add(t);

    }

    void deposit(float f) {

    Transaction t = new Transaction(Transaction.TYPE_DEPOSIT, f, balance);

    balance = t.balance;

    ts.add(t);

    }

    void withdraw(float f) {

    if (balance < f) {

    System.out.println("No enough balance, transaction aborted");

    return;

    }

    Transaction t = new Transaction(Transaction.TYPE_WITHDRAW, f, balance);

    balance = t.balance;

    ts.add(t);

    }

    void showTransactions() {

    if (ts.size() == 0) {

    System.out.println("No transcation.");

    return;

    }

    int cnt = 1;

    while (cnt <= 3) {

    if (ts.size() - cnt < 0) break;

    System.out.println(ts.get(ts.size() - cnt++));

    }

    }

    void showBalance() {

    System.out.println("Balance: $" + balance);

    }

    }

    礙於回答字數有限,完整程式碼請見 http://pastie.org/7460302#2

還有問題?馬上發問,尋求解答。