帮我用java生成一段模拟ATM机的代码,其中包括用户登陆,用户注册,取款,存款,限额,查询账户,注销账户,转账
时间: 2024-10-28 09:06:58 浏览: 27
在Java中,我们可以创建一个简单的模拟ATM机的类,包含相应的功能。这里是一个简化的例子:
```java
import java.util.HashMap;
import java.util.Map;
class User {
private String id;
private double balance;
private boolean isRegistered;
public User(String id) {
this.id = id;
this.balance = 0;
this.isRegistered = false;
}
// 用户注册
public void register() {
if (!isRegistered) {
System.out.println("User " + id + " registered successfully.");
isRegistered = true;
} else {
System.out.println("User already registered.");
}
}
// 存款
public void deposit(double amount) {
if (isRegistered) {
balance += amount;
System.out.println("Deposited " + amount + ". New Balance: " + balance);
} else {
System.out.println("Please register first.");
}
}
// 取款
public void withdraw(double amount) {
if (isRegistered && amount <= balance) {
balance -= amount;
System.out.println("Withdrew " + amount + ". New Balance: " + balance);
} else if (amount > balance) {
System.out.println("Insufficient balance.");
} else {
System.out.println("Not logged in.");
}
}
// 查询余额
public void checkBalance() {
if (isRegistered) {
System.out.println("Current Balance: " + balance);
} else {
System.out.println("Please log in first.");
}
}
// 注销账户
public void logout() {
if (isRegistered) {
System.out.println("User " + id + " has been logged out.");
isRegistered = false;
} else {
System.out.println("You are not logged in.");
}
}
}
public class ATMSimulator {
private Map<String, User> users = new HashMap<>();
// 添加用户注册功能
public void addUser(User user) {
users.put(user.id, user);
}
// 模拟登录
public User login(String id) {
return users.get(id);
}
// 转账
public void transfer(String fromId, String toId, double amount) {
User from = users.get(fromId), to = users.get(toId);
if (from != null && to != null && from.isRegistered && to.isRegistered && amount <= from.balance) {
from.withdraw(amount);
to.deposit(amount);
System.out.println("Transferred " + amount + " from " + fromId + " to " + toId);
} else {
System.out.println("Transfer failed.");
}
}
}
```
这个例子中,我们首先定义了一个`User`类,包含了用户的ID、余额和是否注册的状态。然后在`ATMSimulator`类里实现了用户添加、登录、存款、取款、查询余额、注销以及转账的功能。
阅读全文