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?
First problem: you haven’t overridden
toString()inUser. For example:Second problem: each time an instance of
UserManageris created, you’re changing the values of your static variables… but you’re not doing anything unless an instance ofUserManageris created. One option is to change the constructor of UserManager into a static initializer:Third problem: you haven’t shown us where your
mainmethod is, so we don’t know whether it has access toallTheUsers.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?