Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 更新文本文件中的双精度_Java_File_Bufferedreader - Fatal编程技术网

Java 更新文本文件中的双精度

Java 更新文本文件中的双精度,java,file,bufferedreader,Java,File,Bufferedreader,我有一个ArrayList,其中用户帐户存储在一个文本文件中,每个帐户代表一个虚拟银行帐户 在用户决定增加或取款后,我更新帐户余额的最有效方法是什么 我已成功找回余额,只需保存即可 这是我到目前为止所拥有的,大部分魔法发生在ATM和银行类 ATM类 public class ATM { public static void main(String[] args) throws IOException { Bank bank = new Bank(); double balan

我有一个
ArrayList
,其中用户帐户存储在一个文本文件中,每个帐户代表一个虚拟银行帐户

在用户决定增加或取款后,我更新帐户余额的最有效方法是什么

我已成功找回余额,只需保存即可

这是我到目前为止所拥有的,大部分魔法发生在ATM和银行类

ATM类

public class ATM {

public static void main(String[] args) throws IOException {

    Bank bank = new Bank();
    double balance = 0;

    // Welcome screen
    String dash = "-------------------\n";
    System.out.print(dash);
    System.out.print("Welcome to the Bank\n");
    System.out.print(dash);
    System.out.println("Do you have an account with us? (y/n) ");
    Scanner scanner = new Scanner(System.in);
    String answer = scanner.nextLine();

    while (true) {

    if (answer.equalsIgnoreCase("y")) {

        System.out.println("Username: ");
        String userName = scanner.next();
        System.out.println("PIN: ");
        int pin = scanner.nextInt();

        bank.hasUser(userName, pin);

        if (bank.hasUser(userName, pin)) {
            User.balance = bank.getBalance(userName, pin, balance);
            bank.menu();
            break;
        } else if (!bank.hasUser(userName, pin)) {
            System.out.println("\n** Incorrect username or password, please try again**\n");
        }

    } else if (answer.equalsIgnoreCase("n")) {

        Bank.newUser();
        break;

    } else {
        System.out.println("\nThat's not an option, do you have an account with us?");
    }

    }


}

}
public class Bank {

public static void newUser() {

    // new user is created
    String dash = "-------------------\n";
    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter your full name below (e.g. John M Smith): ");
    String name = scanner.nextLine();
    System.out.println("Create a username: ");
    String userName = scanner.nextLine();
    System.out.println("Enter your starting deposit amount: ");
    double balance = scanner.nextDouble();

    System.out.print(dash);
    System.out.print("Generating your information...\n");
    System.out.print(dash);

    int pin = PIN();
    String accountNum = Bank.accountNum();

    User user = new User(name, userName, pin, accountNum, balance);

    // new user gets added to the array list
    Bank.users.add(user);

    try {

        File file = new File("users.text");
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
        BufferedWriter bw = new BufferedWriter(fw);

        bw.append(String.valueOf(Bank.users + "\n"));
        bw.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void menu() {

    while (true) {

        System.out.print("\n1");
        System.out.print(" - Acount Summary     ");
        System.out.print("3");
        System.out.print(" - Deposit Money\n");
        System.out.print("2");
        System.out.print(" - Withdraw Money     ");
        System.out.print("4");
        System.out.print(" - Exit\n\n");
        System.out.print("I would like to: \n");

        Scanner bscanner = new Scanner(System.in);
        int mc = bscanner.nextInt();

        if (mc == 1) {
            System.out.print("Your current balance is: $"
                    + User.getBalance() + "\n");
        } else if (mc == 2) {
            System.out.print("Enter withdrawl amount: ");
            double wd = bscanner.nextDouble();
            User.balance -= wd;
            System.out.println("\n$" + User.getBalance()
                    + " is your new account balance.");
        } else if (mc == 3) {
            System.out.print("Enter deposit amount: ");
            double dp = bscanner.nextDouble();
            User.balance += dp;
            System.out.println("\n$" + User.getBalance()
                    + " is your new account balance.");
        } else if (mc == 4) {
            System.exit(0);
        } else {
            System.out
                    .print("\nThat's not an option, please select an option listed below!\n");
        }
    }
}

public boolean hasUser(String userName, int pin) {

    try {

        BufferedReader reader = new BufferedReader(new FileReader(
                "users.text"));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.replaceAll("[\\[\\]]", "");
            String[] tokens = line.split(",");
            if (userName.equals(tokens[1])
                    && pin == Integer.parseInt(tokens[3])) {
                return true;
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return false;
}

public double getBalance(String userName, int pin, double balance) {

    boolean r = false;

    try {
        BufferedReader br = new BufferedReader(new FileReader("users.text"));
        String line;
        while ((line = br.readLine())!= null) {
            line = line.replaceAll("[\\[\\]]", "");
            String[] num = line.split(",");
            if (userName.equals(num[1]) && pin == Integer.parseInt(num[3])) {
                r = true;
            }

            if (r) {
                balance = Double.parseDouble(num[4]);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return balance;
}

// array list for users
static ArrayList users = new ArrayList();
{

};
}
银行类

public class ATM {

public static void main(String[] args) throws IOException {

    Bank bank = new Bank();
    double balance = 0;

    // Welcome screen
    String dash = "-------------------\n";
    System.out.print(dash);
    System.out.print("Welcome to the Bank\n");
    System.out.print(dash);
    System.out.println("Do you have an account with us? (y/n) ");
    Scanner scanner = new Scanner(System.in);
    String answer = scanner.nextLine();

    while (true) {

    if (answer.equalsIgnoreCase("y")) {

        System.out.println("Username: ");
        String userName = scanner.next();
        System.out.println("PIN: ");
        int pin = scanner.nextInt();

        bank.hasUser(userName, pin);

        if (bank.hasUser(userName, pin)) {
            User.balance = bank.getBalance(userName, pin, balance);
            bank.menu();
            break;
        } else if (!bank.hasUser(userName, pin)) {
            System.out.println("\n** Incorrect username or password, please try again**\n");
        }

    } else if (answer.equalsIgnoreCase("n")) {

        Bank.newUser();
        break;

    } else {
        System.out.println("\nThat's not an option, do you have an account with us?");
    }

    }


}

}
public class Bank {

public static void newUser() {

    // new user is created
    String dash = "-------------------\n";
    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter your full name below (e.g. John M Smith): ");
    String name = scanner.nextLine();
    System.out.println("Create a username: ");
    String userName = scanner.nextLine();
    System.out.println("Enter your starting deposit amount: ");
    double balance = scanner.nextDouble();

    System.out.print(dash);
    System.out.print("Generating your information...\n");
    System.out.print(dash);

    int pin = PIN();
    String accountNum = Bank.accountNum();

    User user = new User(name, userName, pin, accountNum, balance);

    // new user gets added to the array list
    Bank.users.add(user);

    try {

        File file = new File("users.text");
        if (!file.exists()) {
            file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
        BufferedWriter bw = new BufferedWriter(fw);

        bw.append(String.valueOf(Bank.users + "\n"));
        bw.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void menu() {

    while (true) {

        System.out.print("\n1");
        System.out.print(" - Acount Summary     ");
        System.out.print("3");
        System.out.print(" - Deposit Money\n");
        System.out.print("2");
        System.out.print(" - Withdraw Money     ");
        System.out.print("4");
        System.out.print(" - Exit\n\n");
        System.out.print("I would like to: \n");

        Scanner bscanner = new Scanner(System.in);
        int mc = bscanner.nextInt();

        if (mc == 1) {
            System.out.print("Your current balance is: $"
                    + User.getBalance() + "\n");
        } else if (mc == 2) {
            System.out.print("Enter withdrawl amount: ");
            double wd = bscanner.nextDouble();
            User.balance -= wd;
            System.out.println("\n$" + User.getBalance()
                    + " is your new account balance.");
        } else if (mc == 3) {
            System.out.print("Enter deposit amount: ");
            double dp = bscanner.nextDouble();
            User.balance += dp;
            System.out.println("\n$" + User.getBalance()
                    + " is your new account balance.");
        } else if (mc == 4) {
            System.exit(0);
        } else {
            System.out
                    .print("\nThat's not an option, please select an option listed below!\n");
        }
    }
}

public boolean hasUser(String userName, int pin) {

    try {

        BufferedReader reader = new BufferedReader(new FileReader(
                "users.text"));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.replaceAll("[\\[\\]]", "");
            String[] tokens = line.split(",");
            if (userName.equals(tokens[1])
                    && pin == Integer.parseInt(tokens[3])) {
                return true;
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return false;
}

public double getBalance(String userName, int pin, double balance) {

    boolean r = false;

    try {
        BufferedReader br = new BufferedReader(new FileReader("users.text"));
        String line;
        while ((line = br.readLine())!= null) {
            line = line.replaceAll("[\\[\\]]", "");
            String[] num = line.split(",");
            if (userName.equals(num[1]) && pin == Integer.parseInt(num[3])) {
                r = true;
            }

            if (r) {
                balance = Double.parseDouble(num[4]);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return balance;
}

// array list for users
static ArrayList users = new ArrayList();
{

};
}

一个好方法是将帐户保存在ArrayList中(正如您所做的),然后再次保存整个文本文件。如果您处理的是少量数据,则不会花费很长时间。(考虑优化的更好方法不是每次需要访问文件数据时都重新打开文件,而是将其保存在数组列表中)

此外,您可能不需要在每次更改后保存文件。如果您是唯一使用该文件的应用程序,请尝试在关闭时保存该文件


如果你想要真正好的性能,你需要一个数据库

你必须写入文件,我看不到这些

    File fileWriter = new File("user.txt"); //recall it or whatever
    PrintWriter writer = new PrintWriter(new FileWriter(fileWriter, true)); //APPEND

        writer.println(balance, name, eg...);

    writer.close();
}
Printwriter比filewriter更有效,而且无论如何都需要filewriter,但这也会起作用,如果您想让多人参与,那么只需循环即可,别忘了关闭! for(int i=0;i
如果您仍然有问题,请再次询问我已完成dbms,另一个答案是Wayy off。希望这有帮助!

使用实际的数据库。不允许,这是一个项目,我也不知道如何进行,还是一个业余爱好者……如果文本文件只是用完整和更新的数据覆盖它。不要尝试替换文件的行或部分@zapl这正是我所想的,那么在我进行更改之前,我是否应该将所有用户加载到
ArrayList
,删除该文件,然后将其重新加载到文本文件中?您不必删除该文件。写入文件的默认方式将覆盖内容。好的,我本来打算这样做,但文本文件中的所有内容都没有考虑在内吗一个字符串?那么我必须手动加载和分配每个属性吗?有没有办法将用户保存为对象?@ks23,你需要做的是创建一些类来表示项目。然后当你浏览文件时,你需要从字符串中获取相关数据并将其放入类中。对不起,我无法告诉你如何在java中执行此操作(我的java不好)。我相信我正在向Bank类中的文件写入,在newUser方法中,因此每次创建新用户时,它们都会存储在文件中。我仍在努力拉下每个用户,并将其存储到一个唯一的用户对象中。我必须从列表中拉下每个用户吗?我正在考虑只拉下一个有匹配的用户名和密码,然后当用户添加或提取完钱,用更新的信息覆盖文件中的用户…问题是我甚至不知道从哪里开始。