Problems with JAVA constructor [duplicated]

0

I have problems with this code. I would have to login, but when I enter the username or user name string it does not identify the object I refer to and if it returns a false. I think there is a problem with the constructor attached to both codes.

public class usuario {
    static String nombre;
    static String tipo;
    static String pass;

    public usuario(String nombre_, String tipo_,String pass_) {
        this.nombre=nombre_;
        this.tipo=tipo_;
        this.pass=pass_;
    }

    public String getNombre() {
        return this.nombre;
    }
    public String getTipo() {
        return this.tipo;
    }
    public String getPass() {
        return this.pass;
    }
}

And I try to call from this other class

import javax.swing.*;
import java.util.ArrayList;
class principal {
    public static void main(String[] args) {
        String login;
        usuario[] bd_usuario=new usuario[3];
        JPasswordField jpf = new JPasswordField();
        JLabel titulo = new JLabel ("Ingrese su password");
        bd_usuario[0]=new usuario("Javier","admin","12345");
        bd_usuario[1]=new usuario("fernando","usuario","");
        bd_usuario[2]=new usuario("juan","usuario","");
        String usr;
        int option;
        usr=JOptionPane.showInputDialog(null,"ELIGA UNA OPCION\n\t1.-Iniciar sesion ADMINISTRADOR\n\t2.-Iniciar sesion USUARIO",JOptionPane.INFORMATION_MESSAGE);
        option=Integer.parseInt(usr);
        if (option==1) {
             int cs;
             String name;
             //String contra
             name=JOptionPane.showInputDialog(null,"Ingresa tu USUARIO");

             JOptionPane.showConfirmDialog (null, new Object[]{titulo, jpf}, "Inicio de sesion", JOptionPane.OK_CANCEL_OPTION);
             char p[] = jpf.getPassword();
             String contra= new String(p);
             for(cs=0;cs<3;cs++) {
                 if(name==bd_usuario[cs].getNombre() /*&& contra==bd_usuario[cs].getPass()*/) {
                     m=v1.menu1();
                     while(m>=1 && m<=7)    {
//demas funciones
    
asked by Javier Ale 11.12.2017 в 10:26
source

1 answer

1

Do not compare objects using == , use the .equals(...) method

When you compare two objects using == what you are doing is to compare the pointers to those objects, which will only return true if both objects are the same. With the objects String, Integer ... often the == seems to work , but it is because to save memory you try to reuse the already existing invariable objects, but it is not sure that this happens.

If what you were comparing were objects of a class created by you, then you would have to redefine (overwrite) the equals method, but since you are comparing Strings, it should be enough

if(name!= null && name.equals(bd_usuario[cs].getNombre()) { ...
    
answered by 11.12.2017 в 11:35