java transactions数组_java程序设计 新的account类(transactions数组)

这是一个Java实现的Account类,包含了存款(deposit)、取款(withDraw)操作,使用了线程同步synchronized关键字确保余额操作的安全。同时,Account类记录了所有的交易历史transactions数组,并提供了检查账户信息(checkAccount)的方法,展示存取款记录。
摘要由CSDN通过智能技术生成

满意答案

dcebd7a0de6265b6ccae5ead692f1eab.png

eikey

2014.02.13

dcebd7a0de6265b6ccae5ead692f1eab.png

采纳率:50%    等级:12

已帮助:21596人

用我的,我的绝对比上面那个写得好。(至少用了线程同步synchronized)

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.Date;

import java.util.Iterator;

public class Account {

private String name;

private double balance; // 余额

private int id;

private ArrayList transactions;

public Account(String name, int id, double balance) {

this.name = name;

this.balance = balance;

this.id = id;

this.transactions = new ArrayList();

}

//用同步方法,防止多线程操作导致帐户余额出错

public synchronized void withDraw(double money) throws Exception {

if (money > balance) {

throw new Exception("帐户余额不足!");

} else {

balance -= money;

transactions.add(new Transaction("Withdraw", money));

}

}

//用同步方法,防止多线程操作导致帐户余额出错

public synchronized void deposit(double money) {

balance += money;

transactions.add(new Transaction("Deposit", money));

}

//返回此帐户的所有信息,包括过往存取款纪录

public String checkAccount() {

String msg = "您好!" + name + " 先生,您的帐户余额为: " + balance + " RMB" + "\n"

+ "银行存取纪录:\n";

if (transactions.size() == 0)

return msg + "无";

else {

Iterator it = transactions.iterator();

while (it.hasNext())

msg += it.next().toString() + "\n";

return msg;

}

}

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

Account account = new Account("你妹", 1, 0);

account.deposit(100000);//存10W

//取2次随机数的款项

for (int i = 0; i < 2; i++) {

double money;

money = Math.random() * 1000;

try {

account.withDraw(money);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

//打印帐户所有纪录

System.out.println(account.checkAccount());

}

}

class Transaction {

private Date createdDate; //交易产生的日期

private String operation; //交易的操作

private double money; //交易钱款

public Transaction(String opertaion, double money) {

createdDate = new Date();

this.operation = opertaion;

this.money = money;

}

@Override

public String toString() {

return "[" + new SimpleDateFormat("yyyy-MM-dd").format(createdDate)

+ " " + operation + " " + money + " RMB]";

}

}

02分享举报

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值