1.模拟帐户存取和转账操作
题目:
1、创建账户类Account,内容如下:
(1)成员变量:账户id,实名name、账户余额balance,开户日期dateCreated(Date类型)
(2)构造方法,2个参数,为id和实名赋初值。开户日期为系统当前时间
(3)get和set方法
(4)取款方法withdraw,从账户提取指定数额,余额不足,不可以取款,提示用户
(5)存款方法deposit,向账户存入指定数额
(6)转账方法transfer(Account a,double money),向指定账户转指定数额,余额不足,不可以转账,提示用户
(7)public String toString()方法:返回字符串,格式为“帐号:id\t实名:name\t账户余额:balance\t开户时间: dateCreated(日期要求格式化)”
2、测试类AccountTest
(1)用自己的姓名、学号创建账户对象
(2)使用deposit方法向账户存入3000元,调用toString方法输出账户信息
(3)使用withdraw方法从账户取出2500元,调用toString方法输出账户信息
(4)创建另一个账户对象,向其转账100元,输出两个账户信息
(5)测试取钱和转账时余额不足的情况
Tip:
- 获取当前系统时间是这样
Date dateCreated=new Date();
,并且要引入util中的Date包import java.util.Date;
- 方法转账
void transfer(Account a,double money)
中,”Account a
”的Account是类名,“a
”是对象名,在TextAccount中调用此方法时,a1.transfer(a2, 100);
,对象a2的地址会传递给此处的a
- 在Account类中要把成员变量私有(
private
),并且创建方法用来在其他地方可以通过此方法来访问Account类中的成员变量。 - 转账的方法一定要记得把转账人的余额减掉
代码实现:
以下是Account.java
package Account;
import java.util.Date;
public class Account {
private String id;
private String name;
private double balance;
private Date dateCreated=new Date();
Account(String id,String name){
this.id=id;
this.name=name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
void withdraw(double withdrawMoney) {
if(balance-withdrawMoney<0) {
System.out.println("账户余额不足");
}
else {
balance=balance-withdrawMoney;
System.out.println("成功取款"+withdrawMoney+"元");
}
}
void deposit(double depositMoney) {
balance=balance+depositMoney;
System.out.println("成功存入"+depositMoney+"元");
}
void transfer(Account a,double money) {
if(balance-money<0) {
System.out.println("账户余额不足,不可转账");
}
else {
a.balance=a.balance+money;
balance=balance-money;
System.out.println("成功转入"+money+"元");
}
}
public String toString() {
return "账号:"+id+"\t实名:"+name+"\t账户余额:"+balance+"\t开户时间:"+dateCreated;
}
}
以下是TextAccount.java
package Account;
public class TextAccount {
public static void main(String[] args) {
Account a1=new Account("180430343","夏新澳");
a1.deposit(3000);
System.out.println(a1.toString());
a1.withdraw(2500);
System.out.println(a1.toString());
Account a2=new Account("100000000","某某某");
a1.transfer(a2, 100);
System.out.println(a1.toString());
System.out.println(a2.toString());
a1.withdraw(2500); //测试取钱余额不足
a1.transfer(a2, 800); //测试转账余额不足
System.out.println(a1.toString());
System.out.println(a2.toString());
}
}
运行结果:
成功存入3000.0元
账号:180430343 实名:夏新澳 账户余额:3000.0 开户时间:Wed Feb 27 18:41:59 CST 2019
成功取款2500.0元
账号:180430343 实名:夏新澳 账户余额:500.0 开户时间:Wed Feb 27 18:41:59 CST 2019
成功转入100.0元
账号:180430343 实名:夏新澳 账户余额:400.0 开户时间:Wed Feb 27 18:41:59 CST 2019
账号:100000000 实名:某某某 账户余额:100.0 开户时间:Wed Feb 27 18:41:59 CST 2019
账户余额不足
账户余额不足,不可转账