2017-10-29 127 views
0

我试图将密码程序的登录尝试次数限制为3次,但是当我使用while循环时,即使在第一次尝试输入正确密码时,它也会要求密码3次。这是我到目前为止:限制登录尝试?

import java.util.Scanner; 

public class Password { 

    public static void main(String[] args) { 

    Scanner keyboard = new Scanner(System.in); 

    String password, input; 
    int maxAttempts; 

    password = "Joe"; 
    maxAttempts = 0; 

    while(maxAttempts < 3) 
    { 

    System.out.print("Enter your password: "); 
    input = keyboard.nextLine(); 

    if(input.equals(password)) 

    System.out.println("Congratulations"); 

    else 

    System.out.println("Incorrect. Try Again."); 

    maxAttempts++; 
    } 

    } 
} 
+1

我强烈建议为每个分支或循环使用'{'和'}'字符。也就是说,无论何时写'if','else','for','while'或'do',之后放一个'{',只是为了清楚分支或循环的范围。 –

回答

4

您可以通过放置休息退出while循环;声明。

在你的程序更改以下

if(input.equals(password)) 
     System.out.println("Congratulations"); 

if(input.equals(password)) 
    { 
     System.out.println("Congratulations"); 
     break; 
    } 
0

没有突破上面所说的。该while.only想知道如果尝试超过3不关心,如果密码是正确的。