Why every time I use equals () I get: "java.lang.NullPointerException"? java poo

-1

Good I'm doing poo programs and every time I want to use the equals () method when executing the code I jump in red: "java.lang.NullPointerException", why will it be?

public class Usuario {

private String usuario;
private String contraseña;

public Usuario(String nombre , String contraseña) {

    this.usuario = nombre ;
    this.contraseña = contraseña;
}

public String getNombre () {

    return this.usuario ;
}

public void setNombre(String nombre) {

    this.usuario = nombre ;
}


public String getContraseña() {


    return this.contraseña;
}

public void setContraseña(String contraseña) {


    this.contraseña = contraseña;
}   

}

public class Sistema {

private String nombre;
private Usuario listaDeUsuarios[];
int usuariosAgregados = 0;

public Sistema(String nombre, int cantidadDeUsuarios) {

    this.nombre = nombre;
    this.listaDeUsuarios = new Usuario[cantidadDeUsuarios];

}

public String getNombre() {

    return this.nombre;

}

public void setNombre(String nombre) {

    this.nombre = nombre;
}

public Usuario[] getListaDeAutos(Usuario listaDeUsuarios) {

    return this.listaDeUsuarios;
}

public void setListaDeUsuarios(Usuario[] listaDeUsuarios) {

    this.listaDeUsuarios = listaDeUsuarios;

}

public boolean loguearUsuario(String usuario, String contraseña) {

    boolean estado = false;
    int i = 0;

    for (i = 0; i < listaDeUsuarios.length; i++) {
        if (listaDeUsuarios[i].getNombre().equals(usuario)
                && listaDeUsuarios[i].getContraseña().equals(contraseña)) {

            estado = true;
        }

        else {

            estado = false;
        }
    }

    return estado;
}

public void agregarUsuarios(Usuario usuario) {

    listaDeUsuarios[usuariosAgregados] = usuario;
    usuariosAgregados++;

}

}

    
asked by computer96 09.12.2018 в 06:58
source

2 answers

1

I want to give you several points to correct in your code:

  • Following the good practricas, you must create tucked that you allow to obtain the number of users, thus avoiding using the .length() in your for. (optional)
  • Method agregarUsuarios() You are receiving an object of type User as parameter, which is wrong, should receive the data to CREATE the object of type Usuario in the USERS array listaDeUsuarios[] , thus allowing the use of the CONSTRUCTOR of the User class, which allows creating objects of the User type. Correction:

    public void agregarUsuarios(String nomUser, String contra) {
        listaDeUsuarios[usuariosAgregados] = new Usuario(nomUser, contra);
        usuariosAgregados++;
    }
    
  • Again following good practices, delete the characters of your code, in this case the ñ, avoid using them in the code, only use them in your Strings .
  • Analysis of the problem:

    In summary it is as follows: You are creating a list of users with a defined size, which when you iterate, you iterate over all the spaces, even when they are null , so that, if you have only added 1 user to this arrangement, let's say that in the first iteration you find it, as you are not putting a Break; to for of the method loguearUsuario (), you will continue iterating, even over empty spaces and that's where the error is located, you are telling java that tries to use a function .equals() with a null , which will throw the exception java.lang.NullPointerException .

    Solution:

  • Make all the changes mentioned above.
  • The for of your method loguearUsuario() will have to go from the following way: for (i = 0; i < usuariosAgregados; i++) since you were making it go through all the spaces, including the empty ( null ) and this is what your error is. So, with the Correction previously named, you will only look for the name and password in the fields where there are users stored.
  • Add a break; statement when the name and password is found, because if you do not, when you find it, it will continue iterating, and obviously there will only be one coincidence, so the iterations below will return your status to false .
  • I hope it was helpful, I remain attentive.

        
    answered by 09.12.2018 в 10:48
    1

    Answering your question about Java code Why when I use equals () do I get: "java.lang.NullPointerException"? at least one of the two objects what you are comparing (strings) is null.

    java.lang.NullPointerException (NPE) is common in Java when certain conditions are not controlled. In your case the code fails:

    if (listaDeUsuarios[i].getNombre().equals(usuario)
        && listaDeUsuarios[i].getContraseña().equals(contraseña)) {
            estado = true;
    }
    

    Where usuario and contraseña have been passed to the method that contains it. Before the loop, check if both strings are valid, for example:

    if (usuario == null || contraseña == null) {
        // Aquí puedes generar un mensaje que te advierta que está 
        // fallando, p.e. un mensaje de log
        return false;
    }
    

    include business logic conditions, for example that the password has at least 8 characters, etc.

    if (usuario == null || contraseña == null) {
        // Aquí puedes generar un mensaje que te advierta que está 
        // fallando, p.e. un mensaje de log
        return false;
    }
    if (usuario.equals("") || contraseña.equals("") || contraseña.length < 8) {
        // Aquí puedes generar un mensaje que te advierta que está 
        // fallando, p.e. un mensaje de log
        return false;
    }
    

    You can set local variables with the other values that you are going to compare within the loop and check again if they are null to avoid the NPE:

    String user_to_check = listaDeUsuarios[i].getNombre();
    String pw_to_check   = listaDeUsuarios[i].getContraseña();
    
    if (user_to_check != null && pw_to_check != null) {
        // Aquí puedes guardar un mensaje de log -> todo OK
    
        if (user_to_check.equals(usuario) && pw_to_check.equals(contraseña)) {
            estado = true;
        }
    } else {
        // Aquí puedes generar un mensaje que te advierta que está 
        // fallando, p.e. un mensaje de log
    }
    


    Note: As of Java8 you can also check if you have null values by using the class java.util.Optional to avoid NPE.

    Greetings.

        
    answered by 09.12.2018 в 12:59