It is too important to review the following theory:
First you must know that this:
clave.equals(pass)==false
you can reduce it to:
!clave.equals(pass)
since the equals()
method is actually performing an evaluation, if clave
equals pass
. If we add !
indicates that we are denying it, therefore it means that clave
is NOT equal to pass
.
Now the main problem by which an infinite loop is made is that when starting in reality always clave
will be different to pass
while ((!clave.equals(pass))||(conteo==3)) {
What you should do is evaluate the value of pass
before starting the loop, if the password is incorrect, ask again for the value to the user:
pass=JOptionPane.showInputDialog("Introduce la contraseña");
while ((!clave.equals(pass))||(conteo==3)) {
if (!clave.equals(pass)) {
System.out.println("Contraseña Incorrecta");
pass=JOptionPane.showInputDialog("Introduce la contraseña");
conteo++;
}
}
if the value of clave
and pass
or ( ||
) equals the value of conteo
equals 3, the loop will end.
Now here you can evaluate if the password was correct or simply blocked the computer:
if (clave.equals(pass)) {
System.out.println("CONTRASEÑA CORRECTA");
}else{
System.out.println("EQUIPO BLOQUEADO");
}
Analyze the code:
import javax.swing.*;
public class prueba {
public static void main (String[]args) {
String clave="Juan";
String pass="";
int conteo=0;
pass=JOptionPane.showInputDialog("Introduce la contraseña");
while ((!clave.equals(pass))||(conteo==3)) {
if (!clave.equals(pass)) {
System.out.println("Contraseña Incorrecta");
pass=JOptionPane.showInputDialog("Introduce la contraseña");
conteo++;
}
}
//Después de terminarse el bucle, revisa...
if (clave.equals(pass)) { //Si la contraseña es correcta.
System.out.println("CONTRASEÑA CORRECTA");
}else{//Nunca fue correcta, bloquea el equipo
System.out.println("EQUIPO BLOQUEADO");
}
}