How to implement ATM machine operating system in Java
用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.账户登录
2.查询
3.存款
4.退出
作为数据库的txt文件:
The above is the detailed content of How to implement ATM machine operating system in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
