我正在尝试在 NetBeans 中的 JFrame 表单上创建一个注册窗口。我创建了一个名为 users
的类(在同一个包中),其用户名为 String,密码为 char[]
。
当填写用户名和密码并按下“注册”按钮时,我想在“用户”类中创建一个新对象,以便它的名称取自用户名文本字段本身。
我想动态创建其名称取自字符串的对象。
例如:如果我将用户名的值设置为“guy”
,则创建具有String =“guy”
的users.guy
和一个 char[]
作为密码。
package login;
public class users {
private char[] password;
String username;
users() {
username = "anonymous";
password = null;
}
users(String u, char[] p) {
username = u;
password = p;
}
void putdata() {
System.out.println(username);
System.out.println(password);
}
}
提前致谢。
最佳答案
如果我很好地理解你的问题,你想做的是映射。在 Java 中,有很多方法可以做到这一点。
我推荐你使用HashMap,它简单又高效。 有一个简单的例子。
String userYayotrón = "Yayotrón";
char[] passwordYayotrón = "contraseña".toArray();
Map<String, char[]> usersMap = new HashMap<String, char[]>();
//This hashmap will take two values, the KEY which identifies the VALUE. The key is the first one, which I define as String. I will use it for save the User's name. And the value will be the password.
usersMap.put(userYayotrón,passwordYayotrón);
现在,您可以使用这张 map 做很多事情。例如:
usersMap .get(userYayotrón); // This will return an char[] with the password of Yayotrón.
usersMap .size(); // How many users do you have in this map.
此外,我强烈建议阅读以下相关问题:
关于java - 从字符串动态创建类中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30678811/