Reputation: 3
I have a mother class User and a class that has an array of users as atribute in this class I have this method to sign the users in the ArrayList:
public Class UserArray extends User
public static ArrayList<User> users = new ArrayList<User>(50);
public static void signUser(User u) {
for(User f: users) {
if(u.name.equals(f.name)) {
System.out.println("User already exists");
}
else {
users.add(u);
System.out.println("User signed");
}
}
}
And I have a controler class that should call this method and I tried in two ways(with and without static):
With Static:
public Class Controller extends UserArray
public void signUseron(User u){
UserArray.signUser(u);
System.out.println("Usuario cadastrado com sucesso");
}
And called this method in Main like this:
Controller.signUser(user object);
And tried without static too but I wasnt able to make the sign method and I'm not getting any erros but my array users is with size 0 and I'm been able to add anything to that.
Upvotes: 0
Views: 56
Reputation: 5503
Jeet has pointed out the problem of your code, I just want to provide another possible solution.
Possible Solution:
public static void signUser(User u) {
for(User f: users) {
if(u.name.equals(f.name)) {
System.out.println("User already exists");
return;
}
}
users.add(u);
System.out.println("User signed");
}
Upvotes: 1
Reputation: 547
Your Code:
public Class UserArray extends User
public static ArrayList<User> users = new ArrayList<User>(50);
public static void signUser(User u) {
for(User f: users) {
if(u.name.equals(f.name)) {
System.out.println("User already exists");
}
else {
users.add(u);
System.out.println("User signed");
}
}
}
Lets debug your code:
Possible Solution:
public static void signUser(User u) {
if(!users.isEmpty()){
for(User f: users) {
if(u.name.equals(f.name)) {
System.out.println("User already exists");
}
else {
users.add(u);
System.out.println("User signed");
}
}
} else{
users.add(u.name);
}
}
Upvotes: 0