我正在创建一个邮件系统,有一个我无法弄清楚的小错误。我发布了所有类(class),以防正在阅读的人需要它来理解任何内容,但我显然不希望人们读完所有类(class)。
出现的问题是,当我运行主程序时,我可以创建用户名,但是创建后,用户名不会被存储。
我认为错误要么出现在 main 类中,要么出现在 UserList 类中,但我就是找不到它。我在我认为错误的地方发表了评论。
抱歉,如果我的帖子太长和/或格式不正确。我会删除任何不需要的代码,只需告诉我需要删除的内容即可!
/**
* Created by Broomhead0 on 4/11/14.
*/
import java.util.ArrayList;
public class Userlist
{
//private User[] users; // this is an array that will store references to all users
ArrayList<User> users; //this is an arraylist that will store references to all users
private int numberUsr; // this is the number of users that is currently stored in the user. Always smaller or equal to maxUser
public Userlist()
{
users = new ArrayList<User>();
numberUsr = 0; // at start no user stored yet
}
// find a user in the list based on the username
public User findUser(String username)
{
// iterate through the array; only iterate according to how many users are currently in the array
for (int i = 0; i < numberUsr; i++)
{
// access the particular user through users.(i), then get the name,
// and call the equals method on that name to compare it with the input username
if (users.get(i).userName.equals(username)){
return users.get(i);
}
}
// no user found
return null;
}
//ERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERROR
// add a user to the list; only do so if the user does not yet exist
public void addUser(User u)
{
if (findUser(u.userName) != null) //if there is a match,
System.out.println("User already exists");
else //if there is not match
{
users.add(u); //add the username
}
//ERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERRORERROR
}
}
最佳答案
添加新用户后,numberUsr 保持为 0。当您添加新用户时增加该值,或者在循环用户时更好地使用users.size()
。
public User findUser(String username)
{
// iterate through the array; only iterate according to how many users are currently in the array
for (int i = 0; i < users.size(); i++)
{
// access the particular user through users.(i), then get the name,
// and call the equals method on that name to compare it with the input username
if (users.get(i).userName.equals(username)){
return users.get(i);
}
}
// no user found
return null;
}
关于java - ArrayList不存储值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23020604/