定义一个账户Acount类和Customer类,在Bank类中测试:
模拟银行取钱的机制(加深对参数传递和对象地址的理解)
package com.home.work;
import java.util.Scanner;
/**
* @author Mark-Z
* @version 1.0.1(改进版,增加多种选择)
* @date 2021-10-17
*/
public class Bank {
public static void main(String[] args) throws Exception{
Account account = new Account();
Customer customer = new Customer();
Scanner scanner = new Scanner(System.in);
for (int i = 3;i>0;i--){
System.out.print("请输入你的cid号: ");
int c =scanner.nextInt();
System.out.print("请输入你的cid密码: ");
int p =scanner.nextInt();
if (account.cid==c&&account.cidPassword==p){
while (true){
try {
System.out.print("你是要存钱还是取钱: ");String sc = scanner.next();
if ("存钱".equals(sc)){
System.out.print("你要存多少钱:");
account.withDraw(scanner.nextDouble(),customer);
}
if("取钱".equals(sc)){
System.out.print("你要取多少钱: ");
account.save(scanner.nextDouble(),customer);
}
System.out.println();
}catch (Exception ignored){
System.out.println("error");
}
}
}else {
System.out.println("账号或密码错误!"+"\n");
main(i,c,p,account);
}
}
}
/**
*
* @param i 剩余次数
* @param c 卡号
* @param p 密码
* @param account 对象地址
*/
static void main(int i, int c, int p,Account account) {
if (c==account.cid&&p== account.cidPassword) {
return;
}else{
if(0 !=(i-1)){
System.out.println("输入错误,你还有"+(i-1)+"次机会!");
System.out.print("请重新输入--> ");
}
if(0 ==(i-1)){
System.out.println("拜拜啦,兄弟!");
System.exit(2);
}
}
}
}
class Account{
int cid = 7758258;
int cidPassword = 12345;
double balance = 3854.483;
public String getInfo(){
return ""+"cid: "+cid
+"\n"+ "balance: "
+balance+"(元)";
}
public void withDraw(double d1,Customer customer){
if (d1<100){
System.out.println("存钱失败!最少要100元");
}else {
balance +=d1;
System.out.println("存钱成功");
}
System.out.println(getInfo()+customer.say());
}
public void save(double d2, Customer customer){
if (d2<balance){
balance -=d2;
System.out.println("取钱成功");
System.out.println(getInfo()+customer.say());
}else{
System.out.println("账户内金额小于取出的金额,无法取出");
}
}
}
class Customer{
String name = "Mark";
String address = "地球,太平洋";
int IDnumber = 394613;
int phone = 1877378770;
public String say(){
return "" +"\n"+"姓名:"+ name+"\n"
+"住址:"+ address +"\n"
+"身份证号:"+ IDnumber +"\n"
+"手机号:"+ phone;
}
}
如有不足之处请指正,谢谢。哈哈哈。