写一段java代码,完成类ATM的定义,包括成员变量和成员方法的定义,实现查询功能,取款功能,存款功能,并定义测试类进行测试
时间: 2024-11-05 07:27:55 浏览: 60
```java
// 定义一个ATM类,包含成员变量如账户余额、账户名等
public class ATM {
private double balance;
private String accountName;
// 构造函数初始化余额
public ATM(double initialBalance) {
this.balance = initialBalance;
this.accountName = "匿名账号";
}
// 查询功能:获取当前账户余额
public double queryBalance() {
return balance;
}
// 取款功能:检查余额并减少指定金额
public boolean withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println(accountName + "从ATM机取出了" + amount + "元");
return true;
} else {
System.out.println("取款失败,余额不足!");
return false;
}
}
// 存款功能:增加指定金额到账户
public void deposit(double amount) {
balance += amount;
System.out.println(accountName + "向ATM机存入了" + amount + "元");
}
// 测试类ATMTest用于演示如何使用ATM
public static void main(String[] args) {
ATM atm = new ATM(1000);
atm.withdraw(500); // 验证取款
atm.deposit(200); // 验证存款
System.out.println(atm.queryBalance()); // 输出查询结果
}
}
```
阅读全文