2014-11-24 37 views
0

寫一個程序叫PasswordChecker,做以下後: 1.提示用戶輸入密碼 2.提示用戶重新返回到密碼 3.檢查,以確保兩個密碼輸入相同 4.(前三次嘗試)重複步驟1至3,直到密碼輸入正確兩次。 5.第三次嘗試後,如果用戶沒有正確輸入密碼,程序需要顯示一條提示用戶帳戶被暫停的信息消息。無法獲取代碼終止進入正確的答案

我的代碼:

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); 
} 
} 
+0

您可能要粘貼整個主要方法到右大括號(}),它將使這更容易向你解釋。 – 2014-11-24 03:56:19

回答

4

你似乎缺少一個右括號(打開dowhile之前不要關閉)。你的第一個條件應該是count < 3,我認爲你想循環,而兩個String(s)不相等。喜歡的東西,

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)); 

編輯

您沒有爲Object類型使用==(或!=)的原因是,它僅測試參考平等。您想要測試值是否相等(這些String(s)來自不同的行,因此它們不會通過參考進行比較)。

0

這樣做只是

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++; 
     } 
    } 
}