Paulo Ricardo
Paulo Ricardo

Reputation: 3

Problem with array, not been able to add nothing to him

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

Answers (2)

Yun Zhang
Yun Zhang

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

Jeet Kumar
Jeet Kumar

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:

  1. Very first time when your method signUser () calls then you are trying to iterate users (Arraylist) and it is empty for first time. So nothing will add into users.
  2. Second time, third time.. for the nth time nothing will add into your list.

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

Related Questions