Reputation: 5
Write a program called PasswordChecker that does the following: 1. prompts the user to enter a password 2. prompts the user to renter the password 3. checks to ensure that the two password entries are identical 4. (for the first three attempts) Repeats steps 1 through 3 until the password is correctly entered twice. 5. After the 3rd attempt, if the user doesn’t enter the password correctly, the program needs to display an informative message indicating user account is suspended.
My code:
import java.util.Scanner;
public class passwordChecker{
public static void main(String [] args){
String pw1;
String pw2;
int count=0;
Scanner keyboard = new Scanner(System.in);
do{
System.out.println("Enter the password:");
pw1 = keyboard.nextLine();
System.out.println("Renter the password:");
pw2 = keyboard.nextLine();
count++;
if(pw1.equals(pw2))
System.out.println("Correct");
else if(count>=3)
System.out.println("Account is suspended");
while(pw1==pw2||count>3);
}
}
Upvotes: 0
Views: 50
Reputation: 201467
You seem to be missing a closing brace (you open the do
but don't close before while
). Your first condition should be count < 3
and I think you want to loop while the two String
(s) are not equal. Something like,
do {
System.out.println("Enter the password:");
pw1 = keyboard.nextLine();
System.out.println("Renter the password:");
pw2 = keyboard.nextLine();
count++;
if (pw1.equals(pw2)) {
System.out.println("Correct");
} else if (count >= 3) {
System.out.println("Account is suspended");
}
} while (count < 3 && !pw1.equals(pw2));
Edit
The reason you don't use ==
(or !=
) for Object
types is that it tests reference equality only. You want to test for value equality (these String
(s) came from different lines, so they won't compare equal by reference).
Upvotes: 4
Reputation: 734
Do it simply
public class PasswordChecker {
public static void main(String[] args) {
String pw1;
String pw2;
int count = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the password:");
pw1 = keyboard.nextLine();
while(true){
System.out.println("Renter the password:");
pw2 = keyboard.nextLine();
if (pw1.equals(pw2)) {
System.out.println("Correct");
break;
} else if(count == 3){
System.out.println("Account is suspended");
break;
}
count++;
}
}
}
Upvotes: 0