How to make the Java Scanner read more than once in a program using classes?

Asked

Viewed 150 times

0

I have to make a code using Object Oriented Programming, where you have a password already predefined and using Scanner you enter at least three attempts (one at a time). The program is reading only one attempt, and using the entered value to check every time of 'for', the question is: how to make the program ask at least 3 times what password I want to enter.

main java.

import java.util.Scanner;

public class main{
    public static void main(String[] args) {
        Scanner scanner_tentativa = new Scanner(System.in);
        String tentativa = scanner_tentativa.nextLine();
        Senha senha_banco;
        
        senha_banco = new Senha();
        senha_banco.entraSenha(tentativa);
    }
}

Java password.

public class Senha {
    private String senha;
    private int count;
    private boolean block;
    
    public Senha(){
        this.senha = "123A";
        this.count = 0;
        this.block = false;
    }
    

    public void entraSenha(String tentativa) {
        for (this.count = 0; this.count <= 3; this.count++){
            if (tentativa == this.senha){
                System.out.println("Senha correta");
                this.count = 0;
            }
            else{
                System.out.println("Senha incorreta");
                this.count++;
            }
            if (this.count == 3){
                System.out.println("Senha incorreta");
                System.out.println("Senha bloqueada");
                this.block = true;
            }
        }
    }
  • That? https://answall.com/q/262976/101

  • I removed Line from nextLine but still has the same problem, when I enter the first value it already gives me the "final result", which in case would lock the password.

1 answer

0

There is a serious problem in the class Java password.. In the method entraSenha(String try) You are comparing a String object attempt with another String object password. On the line:

if (tentativa == this.senha){

It will always return false because these objects are different (better explaining: references do not point to the same object). But if you want to compare the strings that these two objects contain, that is, the contents of the strings you can use a method that the String class has:

if (tentativa.equals(this.senha)){

This is a very common logic error.

Browser other questions tagged

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