Just beginning to learn java and I am trying to code a simple password check that gives you tries if you type the incorrect password. The problem is when I type the incorrect password and followed by the correct password it still says its the wrong password.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Tell us the Password");
while(true) {
String password = scanner.nextLine();
if (password.equalsIgnoreCase("Happy")) {
System.out.println("Correct password");
break;
}
else {
for (int i =6; i>0;i--) {
System.out.println("Incorrect password ");
System.out.println( i " Trys left");
password= scanner.nextLine();
}
}
System.out.println("No more tries");
System.out.println("Program exits");
break;
}
}
I want the program to check if the password is correct or incorrect.
CodePudding user response:
Once you entered the wrong password, code flow stuck in the for loop and remain there for available iterations, no comparison with entered password is going on there so you need to modify the flow. One way to do so as per your initial code posted is
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Tell us the Password");
int tryCountForFailure = 6;
while (true) {
String password = scanner.nextLine();
if (password.equalsIgnoreCase("Happy")) {
System.out.println("Correct password");
break;
} else {
System.out.println("Incorrect password ");
System.out.println(tryCountForFailure " Trys left");
tryCountForFailure--;
if (tryCountForFailure == 0) {
System.out.println("No more trys");
System.out.println("Program exits");
break;
}
}
}
scanner.close();
}
CodePudding user response:
In your code, the loop gets stuck in the Else statement. Let's run through the logic.
The program asks for the password and stores it in a password String.
The program check's if that password is right, if it is the program stops and if not it continues to the else statement.
The program uses a for statement to run this block of code 6 times:
System.out.println("Incorrect password "); System.out.println( i " Trys left"); password = scanner.nextLine();
The problem is even if you enter a correct String for the password field, it never checks if that value is correct. You would be better of refactoring your code so the logic is sound. Let's run through what should happen.
- Program defines a variable named
count
and set's it to 0. - The program uses a while loop to ask if count is less than 6.
- The program takes in a password String with a scanner.
- The program checks if that password String is equal to the correct password, if yes, it breaks and,
- If it does not equal the correct password it adds one to
count
Scanner scanner = new Scanner(System.in);
System.out.println("Tell us the Password");
String password = scanner.nextLine();
if (password.equalsIgnoreCase("Happy")) {
System.out.println("Correct password");
break;
} else {
count
}
}