Scanner input = new Scanner(System.in);
final String CORRECT_PASSWORD = "CS1160";
String password;
int count = 0;
//ask for password
System.out.println("Please enter your password: ");
password = input.nextLine();
if(password.equals(CORRECT_PASSWORD)){
System.out.println("You have successfully logged in.");
}
count = 0;
while(count < 3){
while(!password.equals(CORRECT_PASSWORD))
{
System.out.println("Incorrect Password Entered.");
System.out.println("Please enter your password: ");
password=input.nextLine();
count++;
if(password.equals(CORRECT_PASSWORD)){
System.out.println("You have successfully logged in.");
count++;
}}
}
System.out.println("You have been locked out.");
}}
___________________ END _______________________
非常感谢 -SAM
答案 0 :(得分:1)
不要嵌套循环,使用布尔和条件以及一个循环。像,
while(count < 3 && !password.equals(CORRECT_PASSWORD))
答案 1 :(得分:0)
这是因为内在的while循环。在你没有提供正确的密码之前,它不会出现在那里。使用单个while循环,例如:
while(count < 3 && !password.equals(CORRECT_PASSWORD))
然后在这里,你应该写:
System.out.println("Please enter your password: ");
password=input.nextLine();
count++;
if(password.equals(CORRECT_PASSWORD)){
System.out.println("You have successfully logged in.");
break;//brings you out of the while loop as you don't need to check for the password again.
}
count++;