3
public class lookFor {

    //Tools
    //It returns the position of an element at the ArrayList, if not found returns -1
    public int User(String target, ArrayList<User> users){
        for(int i = 0; i < users.size(); i++){
            if(users.get(i).getUserName().equals(target)){
                return i;
            }
        }
        return -1;
    }
}

For some reason, when i try to call "User" This Error appears

And asks me to make the "user" method a static method, but i don't know what repercussion will it have.

nais
  • 105
  • 1
  • 6

4 Answers4

2

A static method belongs to the class, a non-static method belongs to an instance of the class.
You need to create an instance of the class:

 lookFor look = new lookFor();

And write like this:

 if(look.User(username,users)==-1){....};

Static means there is one for an entire class, whereas if it is non-static there is one for each instance of a class (object). In order to reference a non-static method you need to first create an object, and call it.

Abdelhak
  • 8,299
  • 4
  • 22
  • 36
1

You have to make an instance of the lookFor class in order to call it's non-static methods.

lookFor lf = new lookFor();
if(lf.User(username,users)==-1) {
    ...
Stanislav
  • 27,441
  • 9
  • 87
  • 82
1

In order to use the User method in a static context (main method for the example), you need to instantiate the lookFor class and call the User method on that object :

lookFor look = new lookFor(); // Use appropriate constructor
if(look.User(username, users) == -1) {
    ...
}
Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
1

If you are trying to access USER method within static method then you get this error.

The only way to call a non-static method from a static method is to have an instance of the class containing the non-static method. By definition, a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.

For example :

You could create an instance of the class you want to call the method on,

new lookFor().USER(target, list);
Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94