ATM機(遞迴)
阿新 • • 發佈:2018-12-17
ATM機的主要操作如圖所示: 查詢餘額 存款 取款 改密 退卡
package study05; import java.util.Scanner; public class Demo05 { Scanner scan = new Scanner(System.in); int pass = 123456; int money = (int)(Math.random()*1000); int count = 0;//記錄輸入密碼的次數 //登入 public void login() { System.out.println("請輸入密碼:(只有3次機會)"); int pass = scan.nextInt(); //如果登入成功,進入主介面,否則繼續登入 if(this.pass == pass) { mainUI(); }else { if(count <2) { count++; System.out.println("密碼錯誤!請重新登陸!"); login(); }else { System.out.println("對不起!機會用完!請聯絡有關人員!"); } } } //主介面 public void mainUI() { System.out.println("請選擇您要進行的操作:"); int type = scan.nextInt(); switch (type) { case 1: deposit(); break; case 2: withdrawMoney(); break; case 3: search(); break; case 4: changePass(); break; case 5: takeCard(); break; default: break; } } //存款 public void deposit() { System.out.println("請輸入存款金額:"); int money = scan.nextInt(); if(money %100 != 0) { System.out.println("ATM只接收面值100元的人民幣"); deposit(); }else { System.out.println("存款成功!"); this.money += money; mainUI(); } } //取款 public void withdrawMoney() { System.out.println("請輸入你要取款的金額:"); int money = scan.nextInt(); if(this.money < money) { System.out.println("對不起,餘額不足!"); withdrawMoney(); }else { if(money % 100 != 0 ) { System.out.println("請輸入整數金額"); withdrawMoney(); }else { System.out.println("取款成功!"); this.money -= money; mainUI(); } } } //查詢 public void search() { System.out.println("你的餘額為:"+money); mainUI(); } //改密 public void changePass() { System.out.println("請輸入舊密碼:"); int pass = scan.nextInt(); if(this.pass == pass) { System.out.println("請輸入新密碼:"); int newPass1 = scan.nextInt(); System.out.println("請再次輸入密碼:"); int newPass2 = scan.nextInt(); if(newPass1 != newPass2) { System.out.println("兩次密碼不一致,請重新輸入:"); changePass(); }else { System.out.println("修改成功!"); mainUI(); } }else { System.out.println("密碼錯誤!請重新輸入:"); changePass(); } } //退卡 public void takeCard() { System.out.println("謝謝使用!歡迎下次光臨!"); } public static void main(String[] args) { new Demo05().login(); } }