【发布时间】:2014-02-03 04:58:50
【问题描述】:
我本周的任务是创建一个虚拟 ATM,它可以执行基本功能,如添加、取款和检查余额。
我遇到的问题是将用户信息存储在文件中以备后用。
如果用户已经有一个帐户,我需要将他们的所有帐户信息存储在某个地方,这样如果他们有匹配的 ID 和 PIN 码,我就可以将其提取出来。
如果用户没有帐户,那么我需要让他们填写表格,让它生成一个帐号、一个 PIN 以及初始存款。除了将其实际存储到文件中以备后用之外,我已经完成了所有这些工作。
我正在考虑将每个新用户对象存储到ArrayList,然后将其写入外部文件。
但是我以前从来没有这样做过,我一直在四处寻找,但似乎找不到适合我的东西。
所以我的主要问题是,我如何将用户的ArrayList 存储到外部文件中,当用户具有匹配的 ID 和 PIN 时,我如何稍后返回并将它们拉回程序中,这样他们可以从他们的帐户中添加或移除资金。
这是我已有的代码
ATM/主类
import java.util.Scanner;
public class ATM {
public static void main(String[] args) {
//variables
String dash = "-------------------\n";
// Scanner
Scanner scanner = new Scanner(System.in);
//Welcome screen
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) ");
String answer = scanner.nextLine();
if (answer.equalsIgnoreCase("y")) {
} else {
// new user is created
Bank bank = new Bank();
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: ");
int balance = scanner.nextInt();
System.out.print(dash);
System.out.print("Generating your information...\n");
System.out.print(dash);
int pin = bank.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);
System.out.println(user);
}
}
}
带有 PIN、帐号生成器和 ArrayList 的银行类
import java.util.ArrayList;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
public class Bank {
//Generate a random 16 digit bank account number
public String accountNum() {
int max = 9999;
int min = 1000;
int a1 = (int) (Math.random() * (max - min) + min);
int a2 = (int) (Math.random() * (max - min) + min);
int a3 = (int) (Math.random() * (max - min) + min);
int a4 = (int) (Math.random() * (max - min) + min);
String accountNum = a1 + "-" + a2 + "-" + a3 + "-" + a4;
return accountNum;
}
//Generate a random 4 digit PIN
public int PIN() {
int max = 9999;
int min = 1000;
int PIN = (int) (Math.random() * (max - min) + min);
return PIN;
}
//array list for users
@SuppressWarnings("serial")
static ArrayList<User> users = new ArrayList<User>() {
};
}
User类,User对象在这里
public class User {
String name;
String userName;
String accountNum;
int pin;
int balance;
public User(String name, String userName, int pin, String accountNum, int balance) {
this.name = name;
this.userName = userName;
this.accountNum = accountNum;
this.pin = pin;
this.balance = balance;
}
public String toString() {
return "Name: " + this.name + "\n\nUsername: " + this.userName + " | " + "Pin: " + this.pin + "\n\n"
+ "Account Number: " + this.accountNum + "\n\nAccount Balance: $" + this.balance +
"\n\nNever share your login information with anyone!";
}
}
【问题讨论】: