2014-04-11 55 views
0

我正在创建一个邮件系统,这是一个我找不到的小错误。我发布了所有课程,以防读者阅读时需要理解任何内容,但我显然不期望人们读完所有课程。ArrayList不存储值

出现的问题是,当我运行主,我能够创建一个用户名,但是创建它后,用户名不存储。

我认为错误要么在于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 

    } 
} 
+2

您已在此处发布*大量*代码。请尽量减少到更小的程序,这仍然表明您的问题。 –

+2

创建一个最小的,完整的,可验证的示例:http://stackoverflow.com/help/mcve –

+0

尝试写一个小的(如10行)程序来演示问题。这将帮助你缩小真正的问题的范围,并帮助美国轻松搞定。没有人会通读代码页来帮助你处理一个小细节。 – PurpleVermont

回答

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; 
} 
+0

感谢@quaertym和Krzysztof的快速回答! – broomhead0