java 编写一个账户类Account,它包括:一个名为id的int型账号码属性,一个名为balance的double型的账号余额属性,定义一个类型为java.util.Date的属性dateCreated,用于记录账号的创建日期。同时,定义无参的构造函数,一个名为withDraw的方法从账号提取特定数目的金额,此方法返回结果为布尔类型,提取成功为true且余额被减,不成功为false,一个名为deposit的方法向账号存入特定数目的金额。请编写测试程序,测试各个方法。
时间: 2023-06-06 18:05:49 浏览: 130
好的,你的问题是关于 Java 编写一个账户类 Account 的。以下是代码示例:
```
import java.util.Date;
public class Account {
private int id;
private double balance;
private Date dateCreated;
public Account() {
id = 0;
balance = 0.0;
dateCreated = new Date();
}
public Account(int id, double balance) {
this.id = id;
this.balance = balance;
dateCreated = new Date();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public Date getDateCreated() {
return dateCreated;
}
public boolean withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
return true;
} else {
return false;
}
}
public void deposit(double amount) {
balance += amount;
}
}
```
至于测试程序,我们可以这样写:
```
public class TestAccount {
public static void main(String[] args) {
Account a1 = new Account(1001, 5000.0);
System.out.println("Account ID: " + a1.getId());
System.out.println("Account Balance: $" + a1.getBalance());
System.out.println("Account Date Created: " + a1.getDateCreated());
double amount = 2000.0;
boolean result = a1.withdraw(amount);
if (result) {
System.out.println("Withdraw successful. New balance: $" + a1.getBalance());
} else {
System.out.println("Withdraw failed. Insufficient balance.");
}
amount = 8000.0;
a1.deposit(amount);
System.out.println("Deposit successful. New balance: $" + a1.getBalance());
}
}
```
这个测试程序会创建一个账户对象 a1,然后分别测试该账户对象的各个方法。输出结果类似于下面这样:
```
Account ID: 1001
Account Balance: $5000.0
Account Date Created: Thu Jan 31 13:27:34 CST 2019
Withdraw successful. New balance: $3000.0
Deposit successful. New balance: $11000.0
```
希望这样的回答对你有所帮助!
阅读全文