(游戏:ATM 机)使用编程练习题 9.7 中创建的 Account 类来模拟一台 ATM 机。创建一个有 10 个账户的数组,其 id为 0,1,… ,9, 并初始化收支为 100 美元。系统提示用户输人一个id。 如果输人的 id不正确,就要求用户输人正确的 id。一旦接受一个 id, 就显示如运行示例所示 的主菜单。可以选择1来査看当前的收支,选择 2 表示取钱,选择 3 表示存钱,选择 4 表示退 出主菜单。一旦退出,系统就会提示再次输入 id。所以,系统一旦启动就不会停止。
// 模拟ATM
import java.util.Scanner;
public class ATM {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Account1 account = new Account1();
int[] idArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
boolean whether = true;
while (true) {
do {
System.out.print("输入您的账户id: ");
int id = sc.nextInt();
for (int i = 0; i < 10; i++) {
if (id == idArray[i]) {
whether = false;
account = new Account1(id, 100);
break;
}
}
if (whether) {
System.out.println("您的id输入错误,请重新输入: ");
}
}
while (whether);
int a = 0;
while (a != 4){
System.out.printf("%-10s\n%-10s\n%-10s\n%-10s\n%-10s\n", "主菜单",
"1: 查看当前收支", "2: 取钱", "3: 存钱", "4: 退出主菜单");
System.out.print("输入您的选项: ");
a = sc.nextInt();
switch (a) {
case 1: System.out.println("您的收支是: " + account.getBalance()); break;
case 2: System.out.print("请输入您需要取钱的数额: ");
account.withDraw(sc.nextDouble()); break;
case 3: System.out.print("请输入您需要存钱的数额: ");
account.deposit(sc.nextDouble()); break;
case 4: break;
}
}
}
}
}
class Account1{
private int id;
private double balance;
private double annualInterestRate;
private java.util.Date dateCreated;
Account1() {
dateCreated = new java.util.Date();
}
Account1(int id, double balance) {
this.id = id;
this.balance = balance;
dateCreated = new java.util.Date();
}
public int getId() {
return id;
}
public double getBalance() {
return balance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public java.util.Date getDateCreated() {
return dateCreated;
}
public void setId(int id) {
this.id = id;
}
public void setBalance(double balance) {
this.balance = balance;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public double getMonthlyInterestRate() {
return annualInterestRate / 12;
}
public void withDraw(double x) {
balance = balance - x;
}
public void deposit(double y) {
balance = balance + y;
}
}