Login method always returns false

Asked

Viewed 90 times

2

I created a method that returns a Boolean value for access in a program I’m doing. If the user can log in, then returns true, if not, return false. But it’s always coming back false, regardless if the login and password are right, and I’m not understanding why.

I used JOptionPane because it wanted interactions with the user better than simply using System.out.print

   List<String> user = new ArrayList<>();
   List<String> pass = new ArrayList<>();

    //Aqui tem um código onde insiro valores nos ArrayList user e pass. 
    //Que por sinal aparentemente está correto. Printei os arraylist pra ter certeza disso
    //Não coloquei nesse post pois é meio grande.


    public boolean login() {
    String log = JOptionPane.showInputDialog(null, "Digite o login");
    System.out.println("login digitado: "+log);
    String pas = JOptionPane.showInputDialog(null, "Digite a senha");
    System.out.println("Senha digitada: "+pas);
    for (String c : user) {
        System.out.println("valor de 'c' : "+c); 
        //aqui ele printa o valor de 'c'(login), e por sinal esta correto 
        if (c == log) { 
        //mesmo se atribuir o valor correto a 'log' e ele for igual a 'c' o programa não lê este 'if'

            System.out.println("usuario valido"); //isso ñ printa
            for (String s : pass) {
                if (s == pas) {
                    System.out.println("senha válida");
                    return true;
                }
            }
            System.out.println("incompativel senha");
        }
        System.out.println("incompativel login"); //por fim, ele printa isso
    }
    // e sempre retorna false
    return false; //independente se o usuario digitou tudo certo ou ñ
}

Why is this login system not working?

  • I think you logic was pro brejo. Ex: User 1 - Password 123, User 2 - password 456. Now log in with User: User 1 and enter password 456 hehehe. I think someone logged on with a password that doesn’t belong to you hehehe

  • Good afternoon Felipe, welcome to Stack Overflow in Portuguese, I recommend that next time make more intuitive titles to the problem.

1 answer

3


Instead of if(s == pass), do: if(s.equals(pass)).

Same thing for:

if(c == log) 

Do:

if(c.equals(log))
  • Well, leaving a little more clear, what Luiz did above is correct, to compare a string, it is always equals, the "==" for the rest, integer, real, boolean and others.

  • @Luiz thanks so much for the help!

  • 2

    @Brunogomes was worth the explanation! ^^

Browser other questions tagged

You are not signed in. Login or sign up in order to post.