模拟银行账户的登录注册
使用序列化永久保存登录注册信息
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Scanner;
public class ATM {
public static void main(String[] args) throws Exception {
Scanner sc=new Scanner(System.in);
File file=new File("D://test/test2/ATM.txt");
file.createNewFile();
HashMap <String,String> hm=new HashMap<>();
FileOutputStream fos=new FileOutputStream(file,true);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(hm);
oos.flush();
oos.close();
while(true){
System.out.println("请输入要进行的操作:1-登录,2-注册");
String choose=sc.nextLine();
FileInputStream fis=new FileInputStream(file);
ObjectInputStream ois=new ObjectInputStream(fis);
hm = (HashMap<String, String>) ois.readObject();
System.out.println(hm);
if(choose.equals("1")){
System.out.println("请输入账号");
String username = sc.nextLine();
System.out.println("请输入密码");
String password = sc.nextLine();
if(hm.get(username).equals(password)){
System.out.println("登录成功");
}else {
System.out.println("账户密码错误");
}
}
else{
System.out.println("请输入账号");
String username = sc.nextLine();
boolean containsKey = hm.containsKey(username);
if(containsKey){
System.out.println("账户已存在");
}else{
System.out.println("请输入密码");
String password = sc.nextLine();
hm.put(username, password);
ObjectOutputStream oos1=new ObjectOutputStream(new FileOutputStream(file));
oos1.writeObject(hm);
oos1.flush();
oos1.close();
System.out.println("注册成功");
}
}
}
}
}