How do I repeat a password check?

Asked

Viewed 55 times

-2

I am learning Java and decided to make a simple program of login, but I wanted that when the password went wrong he asked again to put the password but I do not know how to do. Can someone help me?

public class PasswordVer {

    public static void main(String[] args){

        Scanner password = new Scanner(System.in);

        String senha1;
        String senha2;
        
        System.out.println("Por favor crie uma nova senha:");
        senha1 = password.nextLine();

        System.out.println("Insira novamente a senha para login:");
        senha2 = password.nextLine();

        if(senha2.equals(senha1)){
            System.out.println("Você agora está logado.");
        }else{
            System.out.println("Senha incorreta. Por favor tente novamente.");
        }

        
    }
    
}
  • 1

    @Solkarped, from what I understand the guy wants to use a do..while or while.

1 answer

-1

One way to implement is by using a repeat command of.. while.

Here’s an example, using your code:

public static void main (String[] args) {
    Scanner password = new Scanner(System.in);
    String senha1,senha2;

    System.out.println("Por favor crie uma nova senha:");
    senha1 = password.nextLine();

    do {
        System.out.println("Insira novamente a senha para login:");
        senha2 = password.nextLine();
        if (senha2.equals(senha1)) {
            System.out.println("Você agora está logado.");
        } else {
            System.out.println("Senha incorreta. Por favor tente novamente.");
        }
    } while (!senha2.equals(senha1));
}

How to know when to use the do..while?

We should use when we know that to accomplish the task there must be pelo menos uma repetição from our code snippet to make a decision. That is our case. Also repair the condition to exit the condicinal command do while. We want the user to keep replying in loop until the password is correct.

  • Thanks buddy, this is just what I needed.

Browser other questions tagged

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