需求:模拟ATM机的存取钱功能
用户类 /** * 用户类 * @author hp * */ public class Person { String name=”zs”;//姓名 int pwd=123456;//密码 } import java.util.Scanner; ATM类 /** * ATM类 * * @author hp * */ public class ATM { double lastMoney = 1000;// 账户余额/** * 插卡开始 */public void start() { boolean flag = login(); if (flag) { Scanner sc = new Scanner(System.in); int num = 0; do { System.out.println("1.查询\t" + "2.存款\t" + "3.取款\t" + "0.退出"); System.out.print("请选择你需要办理的业务:"); num = sc.nextInt(); switch (num) { case 0: exit(); break; case 1: showMoney(); break; case 2: addMoney(); break; case 3: takeMoney(); break; default: System.out.println("您输入数字有误!"); break; } } while (num != 0); }}/** * 登录 */public boolean login() { Person p = new Person(); boolean flag = false; Scanner sc = new Scanner(System.in); for (int i = 0; (i < 3) && (!flag); i++) { System.out.println("请输入用户名:"); String nowName = sc.next(); if (p.name.equals(nowName)) { for (int j = 0; j < 3; j++) { System.out.println("请输入密码:"); int nowPWD = sc.nextInt(); if (nowPWD == p.pwd) { System.out.println("登录成功"); flag = true; break; } else { System.out.println("密码错误,您还有" + (2 - i) + "次机会!"); i++; } } } else { System.out.println("用户名错误,您还有" + (2 - i) + "次机会!"); } } return flag;}/** * 查询方法 */public void showMoney() { System.out.println("****\n当前余额为:" + lastMoney + "****\n");}/** * 存钱方法 */public void addMoney() { Scanner sc = new Scanner(System.in); System.out.print("请输入存款金额:"); double money = sc.nextDouble(); if (money % 100 == 0) { lastMoney += money; System.out.println("存款成功"); } else { System.out.println("存款失败"); } System.out.println("\n****当前余额为:" + lastMoney + "****");}/** * 取钱方法 */public void takeMoney() { Scanner sc = new Scanner(System.in); System.out.print("请输入取款金额:"); double money = sc.nextDouble(); if (money > lastMoney || money % 100 != 0) { System.out.println("取款失败"); } else { lastMoney -= money; System.out.println("取款成功"); } System.out.println("\n****当前余额为:" + lastMoney + "****\n");}/** * 退出方法 */public void exit() { System.out.println("取卡,谢谢使用!");}
}
ATM测试类 /** * ATM测试类 * * @author hp * */ public class ATMTest { public static void main(String[] args) { ATM atm = new ATM(); atm.start(); } } 运行图