2017-10-29 128 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不關心,如果密碼是正確的。