tags:

views:

122

answers:

2

I have this class:

public class User {


    public User(String nickname, String ipAddress) {

        nickname = nickname.toLowerCase();
        System.out.println(nickname + " " + ipAddress);
    }
}

And another class that creates an array containing User objects.

class UserMananger {

    static User user;
    static User user2;
    static User user3;

    static ArrayList allTheUsers;

       public void UserManager() {

           allTheUsers = new ArrayList();

           user = new User("Slavisha", "123.34.34.34");
           user2 = new User("Zare", "123.34.34.34");
           user3 = new User("Smor", "123.34.34.34");

           allTheUsers.add(user);
           allTheUsers.add(user2);
           allTheUsers.add(user3);


       }
}

What I want to do is to call a main method that will give me all elements from the list that are type User in format: "nickname ipAddress"

public static void main(String args[]) {

        System.out.println(allTheUsers.get(0));
    }

For example, this main method should give me something like: Slavisha 123.34.34.34 but it doesn't. What seems to be the problem?

+4  A: 

First problem: you haven't overridden toString() in User. For example:

@Override
public String toString() {
    return nickname + " " + ipAddress;
}

Second problem: each time an instance of UserManager is created, you're changing the values of your static variables... but you're not doing anything unless an instance of UserManager is created. One option is to change the constructor of UserManager into a static initializer:

static {
    // Initialize the static variables here
}

Third problem: you haven't shown us where your main method is, so we don't know whether it has access to allTheUsers.

Fourth problem: "it doesn't" isn't a good description of your problem. Always say what appears to be happening: are you getting an exception? Is it just printing the wrong thing?

Jon Skeet
I did that also but when I compile class User Manager there is an exception:"Exception in thread "main" java.lang.NullPointerException at UserMananger.main(UserManager.java:29)Java Result: 1"
AmateurProgrammer
Right - that would be because you're not calling a constructor, so the initialization code is never getting run.
Jon Skeet
A: 

Solved. Thank you Jon Skeet for your contributions :)

AmateurProgrammer
This should be a comment.
missingfaktor