>Java >java지도 시간 >Java로 ATM 기계 운영 체제를 구현하는 방법

Java로 ATM 기계 운영 체제를 구현하는 방법

王林
王林앞으로
2023-05-14 10:04:121331검색

用IO流操作txt文件作为数据库模拟实现一个ATM业务操作系统---->网上银行,实现登录,查询余额,存款,取款,转账,开户,销户等业务功能

1.用户类----->User:

package atm;

import java.io.Serializable;

public class User implements Serializable{
    
    //建议除了私有属性  无参数有参数构造方法  属性对应的get、set方法
    //建议类实现一个序列化接口 添加一个序列化版本号
    private static final long serialVersionUID = 1L;
    
    //只是为了记录数据库中的一行信息   账号 密码 余额
    private String aName;
    private String aPassword;
    private Float aSalary;
    public User() {}
    public User(String aName,String aPassword,Float aSalary) {
        this.aName = aName;
        this.aPassword = aPassword;
        this.aSalary = aSalary;
    }
    public String getaName() {
        return this.aName;
    }
    public void setaName(String newName) {
        this.aName = newName;
    }
    public String getaPassword() {
        return this.aPassword;
    }
    public void setaPassword(String newPassword) {
        this.aPassword = newPassword;
    }
    public Float getSalary() {
        return this.aSalary;
    }
    public void setSalary(Float newSalary) {
        this.aSalary = newSalary;
    }
}

2.操作IO的类------>FileLoadAndCommit:

package atm;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

//操作文件
public class FileLoadAndCommit {
    
    //文件路径
    private String pathName = null; 
    public FileLoadAndCommit(String pathName) {
        this.pathName = pathName;
    }
    
    //读取文件装入集合
    public HashMap<String,User> loadFile(){
        //临时的存储空间,将文件中读取的数据存储以便于修改
        HashMap<String,User> userBox = new HashMap<String,User>();
        //IO流读取
        FileReader fr = null;
        BufferedReader br = null;
        try {
            fr = new FileReader(new File(pathName));
            br = new BufferedReader(fr);
            String code = br.readLine();//读取一行
            //循环遍历所有行   按"-"拆分一行的数据,作为User存入集合  
            while(code != null) {
                String[] value = code.split("-");
                User user = new User(value[0],value[1],Float.parseFloat(value[2]));
                userBox.put(user.getaName(),user);
                code = br.readLine();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                //如果流管道存在,才关闭
                if(fr != null) {
                    fr.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                if(br != null) {
                    br.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return userBox;
    }
    
    //将集合更新入文件
    public void commit(HashMap<String,User> userBox) {
        //IO流写入
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(new File(pathName));
            bw = new BufferedWriter(fw);
            
            //迭代集合内所有账户名    按账户名找到对应的User对象
            Iterator<String> names = userBox.keySet().iterator();
            while(names.hasNext()) {
                String name = names.next();
                User user = userBox.get(name);
                
                //用StringBuilder拼接字符串
                StringBuilder sBuilder = new StringBuilder();
                sBuilder.append(user.getaName());
                sBuilder.append("-");
                sBuilder.append(user.getaPassword());
                sBuilder.append("-");
                sBuilder.append(user.getSalary());
                bw.write(sBuilder.toString());//将拼好的一行数据写入文件
                bw.flush();//刷新
                bw.newLine();//换行
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            //必须先关闭BufferedWriter再关闭FileWrite,否贼会抛异常java.io.IOException: Stream closed
            try {
                if(bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                if(fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

3.负责读写的类----->AtmDao:

package atm;

import java.util.HashMap;

//持久化,负责读写数据,缓存
public class AtmDao {
    private FileLoadAndCommit flac = new FileLoadAndCommit("D:\\test\\ATM\\testATM.txt");
    HashMap<String,User> userBox = flac.loadFile();
    //获取一个User对象
    public User selectOne(String aName) {
        return userBox.get(aName);
    }
    //更新文件数据
    public void update(User user) {
        userBox.put(user.getaName(),user);
        flac.commit(userBox);
    }
    //删除文件数据
    public void delete(User user) {
        userBox.remove(user.getaName(),user);
        flac.commit(userBox);
    }
}

4.负责业务逻辑的类------>ATMService:

package atm;

import java.util.HashMap;

//负责业务逻辑    判断 比较 计算
public class ATMService {
    //登录
    private AtmDao dao = new AtmDao();
    public String login(String aName,String aPassword) {
        User user = dao.selectOne(aName);
        if(user!=null) {
            if(aPassword.equals(user.getaPassword())) {
                return "登录成功"; 
            }
        }
        return "用户名或密码错误";
    }
    //查询余额
    public Float inquiry(String aName) {
        User user = dao.selectOne(aName);
        return user.getSalary();
    }
    //存款
    public void addMoney(String aName,Float addMoney) {
        User user = dao.selectOne(aName);//获取该用户对象
        user.setSalary(user.getSalary()+addMoney);//用User的set方法修改用户金额
        dao.update(user);//更新文件数据
        System.out.println("存款成功\n");
    }
    //取款
    public void getMoney(String aName,Float getMoney) {
        User user  = dao.selectOne(aName);//获取该用户对象
        if(getMoney <= user.getSalary()) {//如果要取出的钱大于余额就不能取了
            user.setSalary(user.getSalary()-getMoney);
            dao.update(user);
            System.out.println("取款成功\n");
        }else {
            System.out.println("对不起,您的余额不足\n");
        }
    }
    //转账
    public void transferMoney(String outName,String inName,Float transferMoney) {
        User outUser = dao.selectOne(outName);//转出用户
        User inUser = dao.selectOne(inName);//转入用户
        if(inUser!=null) {//转入用户存在
            if(outUser!=inUser) {//转出和转入用户不能是同一个用户
                if(transferMoney <= outUser.getSalary()) {//转出金额大于余额就不能转了
                    outUser.setSalary(outUser.getSalary()-transferMoney);//修改转出用户余额
                    inUser.setSalary(inUser.getSalary()+transferMoney);//修改转入用户余额
                    //更新文件数据
                    dao.update(outUser);
                    dao.update(inUser);
                    System.out.println("转账成功\n");
                }else {
                    System.out.println("对不起"+outName+",您的余额不足\n");
                }
            }else {
                System.out.println("对不起,不能给自己转账,您可以试试使用存款业务\n");
            }
        }else {
            System.out.println("对不起,您输入的用户不存在\n");
        }
    }
    //开户
    public User creatUser(String aName,String aPassword,Float aSalary) {
        User user = new User(aName,aPassword,aSalary);
        dao.update(user);//更新文件数据
        System.out.println("用户"+aName+",创建成功");
        return user;
    }
    //销户
    public void deleteUser(String aName) {
        User user = dao.selectOne(aName);//获取名为aName的用户
        if(user != null) {//判断该用户是否在文件数据内存在
            dao.delete(user);
            System.out.println("用户"+aName+",删除成功");
        }else {
            System.out.println("要销毁的账户不存在");
        }
    }
}

5.测试类----->TestMain:

package atm;

import java.util.Scanner;

public class TestMain {
    public static void main(String[] args) {
        ATMService atmService = new ATMService();//获取执行业务的方法
        Scanner input = new Scanner(System.in);
        System.out.println("欢迎进入ATM机系统");
        System.out.println("请选择要操作的业务:\n1.用户登录\n2.开户\n3.按任意键退出");
        String choice = input.next();
        if(choice.equals("1")) {
            System.out.println("请输入账户名");
            String name = input.next();
            System.out.println("请输入密码");
            String password = input.next();
            String afterLogin = atmService.login(name,password);//判断输入的账户名密码是否正确
            if(afterLogin.equals("登录成功")) {//if正确则登录成功
                System.out.println("登录成功!\n");
                //使用while循环反复进行switch执行操作业务
                while(true) {
                    System.out.println("请选择服务项目:");
                    System.out.println("1.查询\n2.存款\n3.取款\n4.转账\n5.销户\n(按q退出系统)");
                    String option = input.next();
                    switch (option) {
                    case "1":
                        //查询
                        Float money = atmService.inquiry(name);
                        System.out.println("尊敬的客户,您的余额为"+money+"元\n");
                        break;
                    case "2":
                        //存款
                        System.out.println("请输入存款金额");
                        Float addMoney = input.nextFloat();
                        atmService.addMoney(name,addMoney);
                        break;
                    case "3":
                        //取款
                        System.out.println("请输入取款金额");
                        Float getMoney = input.nextFloat();
                        atmService.getMoney(name,getMoney);
                        break;
                    case "4":
                        //转账
                        System.out.println("请输入转账用户ID:");
                        String id = input.next();
                        System.out.println("请输入转账金额:");
                        Float transferMoney = input.nextFloat();
                        atmService.transferMoney(name,id,transferMoney);
                        break;
                    case"5":
                        //销户
                        System.out.println("您确定要销毁当前账户吗?账户内所有余额都会消失\nYes/No\n");
                        String decision = input.next();
                        if(decision.equalsIgnoreCase("yes")) {
                            atmService.deleteUser(name);//删除当前user数据
                        }else if(decision.equalsIgnoreCase("no")){
                             break;
                        }
                        break;
                    case "q":
                        System.out.println("已退出ATM机系统,感谢您的使用!!!");
                        System.exit(0);//退出程序
                        break;
                    default:
                        System.out.println("请输入正确的指令\n");
                        break;
                    }
                }
            }else {
                System.out.println(afterLogin);
            }
        }else if(choice.equals("2")){
            //开户
            System.out.println("请设置您的用户名");
            String newUserName = input.next();
            System.out.println("请设置您的密码");
            String newPassword = input.next();
            User newUser = atmService.creatUser(newUserName, newPassword, 0.0F);
            System.out.println("\n初始余额为"+newUser.getSalary()+"元");
        }else {
            System.out.println("已退出ATM机系统,感谢您的使用!!!");
        }
    }
}

部分运行结果:

1.账户登录

Java로 ATM 기계 운영 체제를 구현하는 방법

2.查询

Java로 ATM 기계 운영 체제를 구현하는 방법

3.存款

Java로 ATM 기계 운영 체제를 구현하는 방법

4.退出

Java로 ATM 기계 운영 체제를 구현하는 방법

作为数据库的txt文件:

Java로 ATM 기계 운영 체제를 구현하는 방법

위 내용은 Java로 ATM 기계 운영 체제를 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제