检查用户名是否已在ArrayList中注册。

huangapple go评论128阅读模式
英文:

Check if username is already registered in ArrayList

问题

我有这个JFrame程序,仅通过用户的全名、用户名、城市和年龄进行注册。我在一个方法中进行了文本字段的检查。如果按下注册JButton,它会检查您是否正确输入了信息,然后创建一个新用户到一个数组列表中。

我需要添加一个检查,当我按下“注册”按钮时,如果用户名已经存在,它会告诉我。我尝试在创建新用户之前的方法中添加一个if语句来检查我的文本字段,但它被忽略了。我还尝试在“注册”按钮的方法之前添加那个if语句,但仍然没有效果。我将在下面粘贴我的Action Listener代码,以及我的方法。

编辑:为了更清楚起见,我发布我用于方法的代码。

public void fieldChecks()
{
    if(fullnameField.getText().length() < 6)
    {
        Helpers.showError("Name must have at least 7 characters");
        return;
    }

    if(usernameField.getText().length() < 4)
    {
        Helpers.showError("Username must have at least 4 characters!");
        return;
    }

    if(cityField.getText().length() < 5)
    {
        Helpers.showError("City must have at least 5 characters");
        return;
    }

    if(passwordField.getText().length() < 8)
    {
        Helpers.showError("Name must have at least 8 characters");
        return;
    }

    if(ageField.getText().length() == 0)
    {
        Helpers.showError("Age is a required field!");
        return;
    }
    //check if our boolean is true or false from Helpers class
    if(Helpers.ageCheck(ageField.getText()) == false)
    {
        Helpers.showError("Age must be a whole number!");
        return;
    }

    String fullname = fullnameField.getText();
    String username = usernameField.getText();
    String city = cityField.getText();
    String password = passwordField.getText();
    int age = Integer.parseInt(ageField.getText());
    String sex = " ";
    //check which radio button is selected
    if(maleOption.isSelected())
    {
        sex = "Male";
    }else
        {
            sex = "Female";
        }

    //we have to create a user now by having the above new vars in the user brackets in order of our Class constructor
    User myUser = new User(fullname,username, city, password, sex, age);

    //create the default add function for our arraylist that we added in the vars above
    myUsers.add(myUser);
    Helpers.showConfirmation("User added!");

}

@Override
public void actionPerformed(ActionEvent e) {

    if(e.getSource() == registerButton)
    {
        //this method checks if my text fields have more 
        //than X charactes typed before it creates a user.
        // This method also adds the new user to my array list 
        //after the checks are complete
        fieldChecks();
    }
    else if(e.getSource() == printButton)
    {
        printUser();
    }
    else if(e.getSource() == searchButton)
    {
        searchUsers();
    }
}
英文:

I have this JFrame program that just registers users by their full name, username, city, age. I have the checks for the text fields in a method. If you press the register JButton, then it checks if you have entered the information correctly and then creates a new User to an array list.

I need to add a check, that will tell me when I press the Register button if the username exists. I tried making an if statement in my method for checking my text fields right before a new user is created in the area list, but it is just ignored. I tried to make that if statement before the method for the Register button and still nothing. I will paste my Action Listener code below, with my methods.

Edit: posting the method that I use for more clarity.

public void fieldChecks()
{
if(fullnameField.getText().length() &lt; 6)
{
Helpers.showError(&quot;Name must have at least 7 characters&quot;);
return;
}
if(usernameField.getText().length() &lt; 4)
{
Helpers.showError(&quot;Username must have at least 4 characters!&quot;);
return;
}
if(cityField.getText().length() &lt; 5)
{
Helpers.showError(&quot;City must have at least 5 characters&quot;);
return;
}
if(passwordField.getText().length() &lt; 8)
{
Helpers.showError(&quot;Name must have at least 8 characters&quot;);
return;
}
if(ageField.getText().length() == 0)
{
Helpers.showError(&quot;Age is a required field!&quot;);
return;
}
//check if our boolean is true or false from Helpers class
if(Helpers.ageCheck(ageField.getText()) == false)
{
Helpers.showError(&quot;Age must be a whole number!&quot;);
return;
}
String fullname = fullnameField.getText();
String username = usernameField.getText();
String city = cityField.getText();
String password = passwordField.getText();
int age = Integer.parseInt(ageField.getText());
String sex = &quot; &quot;;
//check which radio button is selected
if(maleOption.isSelected())
{
sex = &quot;Male&quot;;
}else
{
sex = &quot;Female&quot;;
}
//we have to create a user now by having the above new vars in the user brackets in order of our Class constructor
User myUser = new User(fullname,username, city, password, sex, age);
//create the default add function for our arraylist that we added in the vars above
myUsers.add(myUser);
Helpers.showConfirmation(&quot;User added!&quot;);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == registerButton)
{
//this method checks if my text fields have more 
//than X charactes typed before it creates a user.
// This method also adds the new user to my array list 
//after the checks are complete
fieldChecks();
}
else if(e.getSource() == printButton)
{
printUser();
}
else if(e.getSource() == searchButton)
{
searchUsers();
}

答案1

得分: 0

在此之后:

if(usernameField.getText().length() < 4)
    {
        Helpers.showError("用户名必须至少有4个字符!");
        return;
    }
我将通过以下代码验证是否已使用该用户名

if(myUsers.size() > 0)
    {
       for(User user : myUsers)
          {
              if(usernameField.getText().equals(user.username))
                {
                    Helpers.showError("此用户名已被使用");
                    return;
                }
          }
    }
英文:

After:

if(usernameField.getText().length() &lt; 4)
{
Helpers.showError(&quot;Username must have at least 4 characters!&quot;);
return;
}

I would verify if that username is taken with following code

if(myUsers.size() &gt; 0)
{
for(User user : myUsers)
{
if(usernameField.getText() == user.username)
{
Helpers.showError(&quot;This username is taken&quot;);
return;
}
}
}

答案2

得分: 0

假设myUser是一个类型为myUserArrayList。您想要在myUser类中重写equals方法,然后调用contains方法。查阅如何使用@Override来重写equals方法,以下是一个简短的示例:

public static void main(String[] args) {
    List<myUser> users = new ArrayList<>();

    users.add(new myUser("Billy", "xBillx"));

    List<myUser> usersToAdd = new ArrayList<>();
    usersToAdd.add(new myUser("Jill", "jilly"));
    usersToAdd.add(new myUser("Billy", "xBillx"));

    for (myUser newUser : usersToAdd) {
        if (!users.contains(newUser)) {
            users.add(newUser);
            System.out.println("New user added: " + newUser.fullname);
        } else {
            System.out.println("User already exists " + newUser.fullname);
        }
    }
}

static class myUser {
    final private String fullname;
    final private String username;

    myUser(String fullName, String username) {
        this.fullname = fullName;
        this.username = username;
    }

    @Override
    public boolean equals(Object user) {
        if (user == this) {
            return true;
        }
        if (user instanceof myUser &&
                this.username.equals(((myUser) user).username) &&
                this.fullname.equals(((myUser) user).fullname)) {
            return true;
        }

        return false;
    }
}

它会打印:

New user added: Jill
User already exists Billy

注意:Java中不能使用==来比较字符串。

英文:

I assume that myUser is an ArrayList of type myUser. You want to override equals method in your myUser class and then call contains. Look up how to @Override equals but here is a short demonstration.

public static void main(String[] args) {
List&lt;myUser&gt; users = new ArrayList&lt;&gt;();
users.add(new myUser(&quot;Billy&quot;, &quot;xBillx&quot;));
List&lt;myUser&gt; usersToAdd = new ArrayList&lt;&gt;();
usersToAdd.add(new myUser(&quot;Jill&quot;, &quot;jilly&quot;));
usersToAdd.add(new myUser(&quot;Billy&quot;, &quot;xBillx&quot;));
for(myUser newUser : usersToAdd){
if(!users.contains(newUser)){
users.add(newUser);
System.out.println(&quot;New user added: &quot; + newUser.fullname);
} else {
System.out.println(&quot;User already exists &quot; + newUser.fullname);
}
}
}
static class myUser{
final private String fullname;
final private String username;
myUser(String fullName, String username){
this.fullname = fullName;
this.username = username;
}
@Override
public boolean equals(Object user){
if(user == this){
return true;
}
if(user instanceof myUser &amp;&amp;
this.username.equals(((myUser) user).username) &amp;&amp;
this.fullname.equals(((myUser) user).fullname)) {
return true;
}
return false;
}
}

it prints:

New user added: Jill

User already exists Billy

Edit: made a mistake, you can't compare strings with == in Java

huangapple
  • 本文由 发表于 2020年10月9日 15:01:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64275345.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定