简单的存钱取钱功能模块

做一个简单存钱取钱的存储功能模块。思路如下:
1、数据初始化:当启动main函数的时候,从文本获取初始数据(如:编号,姓名,银行余额等),放入集合里(如:list、map等)。
2、用户可以根据自己的信息在集合查到自己的记录,然后进行存钱取钱操作。
3、当退出的时候,把集合里的信息都反写保存到文本
要求:
代码简单易懂,最好用最基础的知识编写
在以下代码中进行编写改进

public class Test01{
    public static void main(String[] args) throws IOException {
        //创建字符缓冲输入流对象
        BufferedReader br = new BufferedReader(new FileReader("F:\\银行.txt"));

        //创建ArrayList集合对象
        ArrayList<String> array = new ArrayList();

        //调用字符缓冲输入流对象的方法读数据
        String line;
        while ((line=br.readLine())!=null) {
            //把读取到的字符串数据存储到集合中
            array.add(line);
        }

        //释放资源
        br.close();

        //遍历集合输出
        for(String s : array) {
            System.out.println(s);
        }
    }
}

文本文档内容如下:
编号 姓名 性别 银行余额
01 张三 男 1000
02 李四 女 2000

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
 
public class Test01 {
    public static void main(String[] args) throws IOException {
        // 创建字符缓冲输入流对象
        BufferedReader br = new BufferedReader(new FileReader("F:\\银行.txt"));
 
        // 创建集合存储用户信息
        List<Map<String, String>> userList = new ArrayList<>();
 
        // 读取文本文件数据并存储到集合中
        String line;
        while ((line = br.readLine()) != null) {
            String[] userInfo = line.split(" ");
            Map<String, String> userMap = new HashMap<>();
            userMap.put("编号", userInfo[0]);
            userMap.put("姓名", userInfo[1]);
            userMap.put("性别", userInfo[2]);
            userMap.put("银行余额", userInfo[3]);
            userList.add(userMap);
        }
 
        // 释放资源
        br.close();
 
        // 显示用户信息
        for (Map<String, String> user : userList) {
            System.out.println(user);
        }
 
        // 根据用户输入进行存钱取钱操作
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入要进行操作的用户编号:");
        String userInput = scanner.nextLine();
        Map<String, String> selectedUser = null;
 
        for (Map<String, String> user : userList) {
            if (user.get("编号").equals(userInput)) {
                selectedUser = user;
                break;
            }
        }
 
        if (selectedUser != null) {
            System.out.println("当前用户信息:" + selectedUser);
            System.out.println("1. 存钱");
            System.out.println("2. 取钱");
            System.out.print("请选择操作类型(1或2):");
            int action = scanner.nextInt();
 
            if (action == 1) {
                System.out.print("请输入存入金额:");
                int depositAmount = scanner.nextInt();
                int currentBalance = Integer.parseInt(selectedUser.get("银行余额"));
                int newBalance = currentBalance + depositAmount;
                selectedUser.put("银行余额", String.valueOf(newBalance));
                System.out.println("存钱成功!");
            } else if (action == 2) {
                System.out.print("请输入取出金额:");
                int withdrawAmount = scanner.nextInt();
                int currentBalance = Integer.parseInt(selectedUser.get("银行余额"));
 
                if (withdrawAmount > currentBalance) {
                    System.out.println("余额不足,取钱失败!");
                } else {
                    int newBalance = currentBalance - withdrawAmount;
                    selectedUser.put("银行余额", String.valueOf(newBalance));
                    System.out.println("取钱成功!");
                }
            } else {
                System.out.println("无效的操作类型!");
            }
        } else {
            System.out.println("找不到对应编号的用户!");
        }
 
        // 保存用户信息到文本文件
        BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\银行.txt"));
 
        for (Map<String, String> user : userList) {
            StringBuilder sb = new StringBuilder();
            sb.append(user.get("编号")).append(" ")
                    .append(user.get("姓名")).append(" ")
                    .append(user.get("性别")).append(" ")
                    .append(user.get("银行余额"));
            bw.write(sb.toString());
            bw.newLine();
        }
 
        // 释放资源
        bw.close();
    }
}

该回答引用自ChatGPT:根据您提供的代码和需求,我理解您需要编写一个简单的存钱取钱的功能模块,并在程序运行时从文本文件中加载初始数据,然后将更新后的数据保存回文本文件。以下是基于您的思路进行改进的Java代码示例:

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Test01 {
    public static void main(String[] args) {
        List<String> array = new ArrayList<>();

        try {
            // 从文本文件中读取初始数据
            BufferedReader br = new BufferedReader(new FileReader("F:\\银行.txt"));
            String line;
            while ((line = br.readLine()) != null) {
                array.add(line);
            }
            br.close();
        } catch (IOException e) {
            System.out.println("读取文件出错:" + e.getMessage());
        }

        // 显示初始数据
        System.out.println("初始数据:");
        for (String s : array) {
            System.out.println(s);
        }

        // 根据用户信息查找记录,并进行存钱和取钱操作
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入您的编号:");
        String id = scanner.nextLine();
        boolean found = false;

        for (int i = 0; i < array.size(); i++) {
            String record = array.get(i);
            if (record.startsWith(id)) {
                found = true;
                String[] fields = record.split(" ");
                String name = fields[1];
                String gender = fields[2];
                int balance = Integer.parseInt(fields[3]);

                System.out.println("欢迎," + name + ",您当前的银行余额为:" + balance);
                System.out.println("请选择操作:1. 存钱  2. 取钱");
                int choice = scanner.nextInt();

                if (choice == 1) {
                    System.out.println("请输入存款金额:");
                    int deposit = scanner.nextInt();
                    balance += deposit;
                    array.set(i, id + " " + name + " " + gender + " " + balance);
                    System.out.println("存钱成功!当前银行余额为:" + balance);
                } else if (choice == 2) {
                    System.out.println("请输入取款金额:");
                    int withdrawal = scanner.nextInt();
                    if (withdrawal <= balance) {
                        balance -= withdrawal;
                        array.set(i, id + " " + name + " " + gender + " " + balance);
                        System.out.println("取钱成功!当前银行余额为:" + balance);
                    } else {
                        System.out.println("余额不足,取钱失败!");
                    }
                } else {
                    System.out.println("无效操作!");
                }

                break;
            }
        }

        if (!found) {
            System.out.println("未找到对应的用户记录!");
        }

        scanner.close();

        // 将更新后的数据保存回文本文件
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter("F:\\银行.txt"));
            for (String record : array) {
                bw.write(record);
                bw.newLine();
            }
            bw.close();
        } catch (IOException e) {
            System.out.println("保存文件出错:" + e.getMessage());
        }
    }
}

请注意,上述代码是基于您提供的文本文件格式进行解析和操作的。每一行记录都被视为一个字符串,并按空格分隔为不同字段。您可以根据实际的文本文件格式进行适当的调整。

此代码示例使用ArrayList来存储从文本文件中读取的记录,根据用户输入的编号查找对应的记录,并进行存钱和取钱操作。操作完成后,更新后的数据将保存回文本文件。

请确保文件路径和文件格式的正确性,并根据需要进行适当的错误处理。

import java.io.*;
import java.util.*;

public class Bank {
    private static final String FILENAME = "bank.txt"; // 文件名
    private Map<String, Double> records; // 存储所有人的记录

    public Bank() throws IOException {
        File file = new File(FILENAME);
        if (file.exists()) { // 如果文件存在,从文件中读取数据
            loadRecords();
        } else { // 如果文件不存在,创建空白文件
            file.createNewFile();
            records = new HashMap<>();
        }
    }

    // 从文件中读取记录
    private void loadRecords() throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(FILENAME));
        records = new HashMap<>();

        String line;
        while ((line = reader.readLine()) != null) {
            String[] parts = line.split(" ");
            String name = parts[0];
            double balance = Double.parseDouble(parts[1]);
            records.put(name, balance);
        }

        reader.close();
    }

    // 将记录保存到文件中
    public void saveRecords() throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter(FILENAME));

        for (String name : records.keySet()) {
            double balance = records.get(name);
            String line = name + " " + balance;
            writer.write(line);
            writer.newLine();
        }

        writer.close();
    }

    // 存钱
    public void deposit(String name, double amount) throws Exception {
        if (!records.containsKey(name)) {
            throw new Exception("No such person");
        }

        double balance = records.get(name);
        balance += amount;
        records.put(name, balance);
    }

    // 取钱
    public void withdraw(String name, double amount) throws Exception {
        if (!records.containsKey(name)) {
            throw new Exception("No such person");
        }

        double balance = records.get(name);
        balance -= amount;
        if (balance < 0) {
            throw new Exception("Insufficient balance");
        }
        records.put(name, balance);
    }

    // 获取余额
    public double getBalance(String name) throws Exception {
        if (!records.containsKey(name)) {
            throw new Exception("No such person");
        }

        return records.get(name);
    }

    public static void main(String[] args) throws IOException {
        Bank bank = new Bank();
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("1. Deposit");
            System.out.println("2. Withdraw");
            System.out.println("3. Get balance");
            System.out.println("4. Quit");
            System.out.print("> ");

            int choice = scanner.nextInt();
            if (choice == 1) {
                System.out.print("Name: ");
                String name = scanner.next();

                System.out.print("Amount: ");
                double amount = scanner.nextDouble();

                try {
                    bank.deposit(name, amount);
                    System.out.println("Deposit successful");
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else if (choice == 2) {
                System.out.print("Name: ");
                String name = scanner.next();

                System.out.print("Amount: ");
                double amount = scanner.nextDouble();

                try {
                    bank.withdraw(name, amount);
                    System.out.println("Withdrawal successful");
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else if (choice == 3) {
                System.out.print("Name: ");
                String name = scanner.next();

                try {
                    double balance = bank.getBalance(name);
                    System.out.println("Balance: " + balance);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            } else if (choice == 4) {
                try {
                    bank.saveRecords();
                    System.out.println("Goodbye!");
                    break;
                } catch (Exception e) {
                    System.out.println("Failed to save records");
                }
            } else {
                System.out.println("Invalid choice");
            }

            System.out.println();
        }

        scanner.close();
    }
}

这个实现使用了一个 Map<String, Double> 来存储记录,其中键是人的姓名,值是银行余额。在程序启动时,它会尝试从文件中读取数据,如果文件不存在,就创建一个新的空白文件。在程序退出时,它会将所有记录保存回文件中。