如何用Java编程语言来设计和实现一个基础的银行ATM(自动取款机)系统?
时间: 2024-12-23 09:23:42 浏览: 0
设计一个基本的银行ATM系统,我们可以使用Java来创建几个类来模拟机器的功能和用户交互。以下是一个简单的示例:
1. **Account** 类:代表用户的账户,包含账户余额、户名等属性。
```java
public class Account {
private double balance;
private String holderName;
public Account(double initialBalance, String name) {
this.balance = initialBalance;
this.holderName = name;
}
// getters and setters...
public double getBalance() { return balance; }
public void deposit(double amount) { balance += amount; }
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
} else {
System.out.println("Insufficient balance.");
}
}
}
```
2. **ATM** 类:作为银行ATM的实体,负责与用户交互并处理操作。
```java
import java.util.Scanner;
public class ATM {
private Account account;
public ATM(Account account) {
this.account = account;
}
public void startSession() {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Select an option:");
System.out.println("1. Check Balance");
System.out.println("2. Deposit");
System.out.println("3. Withdraw");
System.out.println("4. Exit");
int choice = scanner.nextInt();
switch (choice) {
case 1:
displayBalance();
break;
case 2:
handleDeposit(scanner.nextDouble());
break;
case 3:
handleWithdraw(scanner.nextDouble());
break;
case 4:
System.out.println("Thank you for using the ATM. Goodbye!");
return;
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
private void displayBalance() {
System.out.printf("Your current balance is %.2f\n", account.getBalance());
}
private void handleDeposit(double amount) {
account.deposit(amount);
displayBalance();
}
private void handleWithdraw(double amount) {
account.withdraw(amount);
displayBalance();
}
}
```
3. **Main** 类用于测试ATM。
```java
public class Main {
public static void main(String[] args) {
Account userAccount = new Account(5000, "John Doe");
ATM atm = new ATM(userAccount);
atm.startSession();
}
}
```
在这个例子中,用户通过ATM选择操作,如查看余额、存款和取款。ATM会根据用户输入执行相应的账户操作。
阅读全文