如何将新对象参数存储为HashMap的值?代码问题求助
问题:注册用户信息无法正确存入HashMap
我尝试将注册窗口输入的用户名、密码等用户信息存储到HashMap中,计划用username作为键,对应值为完整的Client对象,但目前无法正确保存输入的参数。以下是现有代码:
Client.class
public class Client { public String name; public String username; public String password; public Double balance; public String address; public String phone; private ArrayList<Account> accounts; // Default Constructor public Client() { name = ""; address = ""; phone = ""; username = ""; password = ""; balance = 0.0; } // Parameterized Constructor public Client(String name, String username,String password, String phone, String address, Date date) { this.name = name; this.username = username; this.password = password; this.address = address; this.phone = phone; accounts = new ArrayList<>(); } public ArrayList<Account> getStringList(String acc_num, String From, String To) { return accounts; } public void setStringList(ArrayList<Account> accounts) { this.accounts = accounts; } void showClientInfo() { System.out.println("Name: "+name); System.out.println("Phone Name: "+phone); System.out.println("Address Name: "+address); } public Account getAccount(String acctNum) { for(Account a: accounts) { if(acctNum.equals(a.getAccountNumber())) { return a; } } return null; } public boolean removeAccount(String acctNum) { Account a = getAccount(acctNum); if(a != null) { a.setActive(false); accounts.remove(a); return true; } return false; } public String getName() { return name; } public void setName(String name) { if (name != null && !name.isEmpty()) { this.name = name; } } public String getPhone() { return phone; } public void setPhone(String phone) { if (phone != null && !phone.isEmpty()) { this.phone = phone; } } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } // end of class }
Bank_Account.class
// Bank_Account Class public class Bank_Account { public Client newClient = new Client(); public String username,password; public static HashMap<String, Client> clientMap; // constructor public Bank_Account(String username, String password) { this.username = username; this.password = password; clientMap = new HashMap<String, Client>(); } // updates the object member variables public void addInfo(String username, String password, String name, String address, String phone) { newClient = new Client(username, password, name, address, phone, new Date()); if (newClient != null) { clientMap.put(newClient.getUsername(), newClient); } } public boolean closeAccount(String username, String acctNum) { Client client = clientMap.get(username); if (client != null) { return client.removeAccount(acctNum); } return false; } public static void displayCustomerInformation(Client client){ if(client != null){ System.out.println(client); } } public static Map<String, Client> getLoginInfo() { return clientMap; } public int addAmount(int b) { return 0; } public static String getDate() { return getDate(); } public int removeAmount(int b) { return 0; } public void updateBalance() { } public void finalize() { System.out.println("Bank Account Destructor"); } // end of class }
Sign up GUI.class
//function executed when Verify Account Button is clicked btn_Create_Account.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //set username/password text field as parameter for bank account constructor Bank_Account bank = new Bank_Account(tf_UserName.getText(), tf_Pass.getText()); //save username/password text field String userId = tf_UserName.getText(); String password = tf_Pass.getText(); // check if user exists if (Bank_Account.clientMap.containsKey(userId)) { System.out.println("usernmae already exists " + userId ); JOptionPane.showMessageDialog(f,"username already exists "); } //check if password created contains specials characters else if(!password.matches((((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*_]).{8,})))) { JOptionPane.showMessageDialog(f, "Invalid password condition. Set again :"); } //if user does not exist put inside hashmap and insert password inside client class else { System.out.println(Bank_Account.clientMap); Bank_Account.clientMap.put(userId, client); JOptionPane.showMessageDialog(f, "Account registered successfully " ); // ************************************** System.out.println("account registered "+ Bank_Account.clientMap.get(userId) + Bank_Account.getLoginInfo()); frame.remove(f); frame.repaint(); frame.validate(); openSignInForm(frame, client); } } }); }
问题分析与修复方案
核心问题点
- 静态
clientMap被重复初始化
每次点击按钮创建Bank_Account实例时,构造方法都会重新创建一个新的HashMap,导致之前存储的用户信息全部丢失。 - GUI代码未初始化
Client对象
注册逻辑中直接使用未初始化的client变量存入Map,导致存入的是无效对象。 getDate()方法无限递归return getDate();会触发无限递归,最终导致栈溢出。
修复步骤
1. 修正Bank_Account类的静态Map初始化
将静态Map的初始化移到静态代码块,确保只执行一次:
public class Bank_Account { public Client newClient = new Client(); public String username,password; public static HashMap<String, Client> clientMap; // 静态初始化块,仅在类加载时执行一次 static { clientMap = new HashMap<String, Client>(); } // 构造方法移除Map初始化逻辑 public Bank_Account(String username, String password) { this.username = username; this.password = password; } // 修复getDate()方法,返回当前时间字符串 public static String getDate() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); } // 其他方法保持不变... }
2. 修正GUI注册逻辑
先收集所有用户输入,创建完整的Client对象后再存入Map:
btn_Create_Account.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String userId = tf_UserName.getText(); String password = tf_Pass.getText(); // 假设存在对应输入框获取姓名、地址、电话 String name = tf_Name.getText(); String address = tf_Address.getText(); String phone = tf_Phone.getText(); // 先检查用户是否存在,避免重复创建实例 if (Bank_Account.clientMap.containsKey(userId)) { System.out.println("username already exists " + userId ); JOptionPane.showMessageDialog(f,"username already exists "); } else if(!password.matches("(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*_]).{8,}")) { JOptionPane.showMessageDialog(f, "Invalid password condition. Set again :"); } else { // 创建完整的Client对象 Client newClient = new Client(name, userId, password, phone, address, new Date()); Bank_Account.clientMap.put(userId, newClient); JOptionPane.showMessageDialog(f, "Account registered successfully " ); System.out.println("account registered "+ Bank_Account.clientMap.get(userId)); frame.remove(f); frame.repaint(); frame.validate(); openSignInForm(frame, newClient); } } });
3. 可选:为Client类添加toString()方法
方便打印查看用户信息:
@Override public String toString() { return "Client{" + "name='" + name + '\'' + ", username='" + username + '\'' + ", address='" + address + '\'' + ", phone='" + phone + '\'' + '}'; }
内容的提问来源于stack exchange,提问作者sillyconAdmin
相关产品推荐
相关产品推荐

