我正在创建一个邮件系统,而且这是一个我无法弄清楚的小错误。我正在发布所有课程,以防任何人在阅读时需要了解任何内容,但我显然不希望人们阅读所有内容。
出现的问题是,当我运行main时,我可以创建用户名,但是在创建后,用户名不会被存储。
我认为错误存在于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
}
}
答案 0 :(得分:1)
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;
}