用java方法写简易ATM,供大家参考,具体内容如下
本文需求:用java写一个简易ATM
功能:有登陆,有查询资金功能,有存款功能,有取款功能,有转账功能,有退出;
简述: (java方法)类似于javascript中的函数,用于封装一些代码,以便代码的复用;
技术需求:方法
效果如下:
代码如下:
package com.atm;
import java.util.Scanner;
public class Atm {
public Scanner scanner = new Scanner(System.in);
public String[] cardNos= {"123","456","111"};
public String[] passwords= {"112","223","121"};
public String[] userNames= {"小张","小小","张晓"};
public double[] moneys = {1000,2000,3000};
public int userIndex = 10;
public int time=3;
public static void main(String[] args) {
Atm atm = new Atm();
atm.atmRun();
}
public void atmRun() {
while(time>0) {
System.out.println("请输入卡号:");
String cardNo = scanner.nextLine();
System.out.println("请输入密码:");
String pwd = scanner.nextLine();
int userIndex= this.login(cardNo, pwd);
if(userIndex!=10) {
this.showMenu();
}else {
time --;
System.out.println("您输入的账号或密码有误");
System.out.println("你还有"+time+"次机会");
}
if(time==0) {
System.exit(0);
}
}
}
public int login(String cardNo,String pwd) {
for(int i=0;i<cardNos.length;i++) {
if(cardNo.equals(cardNos[i])) {
userIndex=i;
break;
}
}
if(userIndex!=10) {
if(pwd.equals(passwords[userIndex])) {
return userIndex;
}else {
userIndex=10;
}
}
return userIndex;
}
public void showMenu() {
time=0;
int out=10;
System.out.println("欢迎尊敬的VIP用户: "+userNames[userIndex]);
while(out==10) {
System.out.println("请选择你的操作: 1 查询 2 取款 3 存款 4 转账 5 退出");
int getNum=scanner.nextInt();
switch (getNum) {
case 1:System.out.println("您当前余额为:"+moneys[userIndex]);
break;
case 2:this.getMoneys();
break;
case 3:this.savaMoney();
break;
case 4:this.transMoneys();
break;
case 5: System.out.println("退出成功!");
out=0;
}
}
}
public void getMoneys() {
System.out.println("请输入您的取款金额:");
int getMoney=scanner.nextInt();
if(getMoney>moneys[userIndex]) {
System.out.println("亲亲您的余额不足哦!!!");
System.out.println("您的余额为:"+moneys[userIndex]);
}else {
moneys[userIndex]-=getMoney;
System.out.println("亲恭喜您成功取款"+getMoney+" 您的余额为: "+moneys[userIndex]);
}
}
public void savaMoney() {
System.out.println("请输入您的存款金额:");
int savaMoney=scanner.nextInt();
moneys[userIndex]+=savaMoney;
System.out.println("亲恭喜您成功存款"+savaMoney+" 您的余额为: "+moneys[userIndex]);
}
public void transMoneys() {
int hasUser=10;
int transIndex=0;
System.out.println("请输入转账的账号:");
String transCard=scanner.next();
for(int i=0;i<cardNos.length;i++) {
if(transCard.equals(cardNos[i])) {
hasUser=5;
transIndex=i;
break;
}
}
if(hasUser==10) {
System.out.println("亲亲,此账号不纯在哦!!");
}else {
System.out.println("请输入转账金额:");
double transMoney=scanner.nextDouble();
if(transMoney>moneys[userIndex]) {
System.out.println("转账失败!!");
System.out.println("失败原因:转账金额大于余额,您的余额为:"+moneys[userIndex]);
}else {
transCard+=transMoney;
moneys[userIndex]-=transMoney;
System.out.println("成功向:"+userNames[transIndex]+"转账:"+transMoney);
System.out.println("您剩余金额为:"+moneys[userIndex]);
}
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。