用java编写一个基本账户类,成员变量包含账号,储户姓名和存款金额,方法有存款和取款。编写一个测试程序来测试所定义的账号类是否能实现存款和取款功能
时间: 2024-06-10 20:06:28 浏览: 15
好的,这是一个Java编写基本账户类的代码示例:
```
public class Account {
private String accountNumber; // 账号
private String accountHolder; // 储户姓名
private double balance; // 存款金额
public Account(String accountNumber, String accountHolder, double balance) {
this.accountNumber = accountNumber;
this.accountHolder = accountHolder;
this.balance = balance;
}
public void deposit(double amount) {
balance += amount;
System.out.println("已存入" + amount + "元,当前余额:" + balance + "元。");
}
public void withdraw(double amount) {
if (balance < amount) {
System.out.println("余额不足,无法取款!");
} else {
balance -= amount;
System.out.println("已取出" + amount + "元,当前余额:" + balance + "元。");
}
}
public void display() {
System.out.println("账号:" + accountNumber + ",储户姓名:" + accountHolder + ",当前余额:" + balance + "元。");
}
}
```
这个基本账户类包含了账号、储户姓名以及存款金额等成员变量,和存款和取款等方法。在存款和取款方法中,都会改变账户的余额,并输出操作后的余额信息。在测试程序中,可以创建一个Account对象,调用方法来测试所定义的账号类是否能实现存款和取款功能:
```
public class AccountTest {
public static void main(String[] args) {
Account account = new Account("1234567890", "张三", 1000.0);
account.display();
account.deposit(500.0);
account.withdraw(200.0);
account.display();
}
}
```
运行这个测试程序,可以看到输出的结果:
```
账号:1234567890,储户姓名:张三,当前余额:1000.0元。
已存入500.0元,当前余额:1500.0元。
已取出200.0元,当前余额:1300.0元。
账号:1234567890,储户姓名:张三,当前余额:1300.0元。
```
说明这个基本账户类能够实现存款和取款功能,并且操作后的余额信息正确。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)