1) 定义一个交易类Transaction,记录每次交易的交易帐户、交易时间、交易额和交易是否成功,覆盖toString()方法,按一下格式返回对象信息:
交易帐户,yyyy-mm-dd hh:MM、交易额、Y|N
2) 定义一个银行账户类Account,包括:
² 属性:账户名称name,String型
² 账户号码id,String 型
² 存款余额balance,double型
² 操作记录transList,List型
² 构造函数:Account(String name,double balance,String aid);
² 取款操作方法void deposite(double amount),更新用户余额的同时生成transaction对象保存在transList中;
² 存款操作方法void withdraw (double amount),更新用户余额的同时生成transaction对象保存在transList中;
² 查询用户操作记录的方法getTransList()方法,在此方法中,将transList中记录的所有用户的操作信息在控制台进行输出;
定义一个测试类Test,包含main方法,在main方法中创建Account对象,并调用deposite,withdraw,getTransList方法,测试实现的功能
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
class Transaction{
public String Tran_time;
public String Tran_name;
public Double Tran_amount;
public String Tran_status;
Transaction(String name,String string,Double amount,String status){
Tran_name=name;
Tran_time=string;
Tran_amount=amount;
Tran_status=status;
}
@Override
public String toString(){
return "交易账户:"+Tran_name+"\n"+"交易时间:"+Tran_time+"\n"+"交易金额:"+Tran_amount+"\n"+"交易状态:"+Tran_status+"\n\n\n";
}
}
class Account{
String name;
String id;
Double balance;
ArrayList transList=new ArrayList();
Account(String name,double balance,String aid){
this.name=name;
this.id=aid;
this.balance=balance;
}
public void deposite(double amount){
balance+=amount;
Transaction tran_deposite=new Transaction(this.id,DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM).format(new Date()),amount,"Y");
this.transList.add(tran_deposite);
}
public void withdraw (double amount){
if(balance>=amount){
balance-=amount;
Transaction tran_deposite=new Transaction(this.id,DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM).format(new Date()),-amount,"Y");
this.transList.add(tran_deposite);
}
else {
Transaction tran_deposite=new Transaction(this.id,DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM).format(new Date()),0.0,"N(余额不足!)");
this.transList.add(tran_deposite);
}
}
public void getTransList(){
Iterator a=transList.iterator();
System.out.print("当前账户余额:"+this.balance+"\n");
while(a.hasNext()){
Object element=a.next();
System.out.print(element.toString());
}
}
}
public class test {
public static void main(String args[]){
Account myaccount=new Account("小林",1000.0,"123456789");
myaccount.deposite(200.0);
myaccount.withdraw(300.0);
myaccount.deposite(500.0);
myaccount.withdraw(20000.0);
myaccount.getTransList();
}
}