2014-04-11 76 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