2017-03-01 53 views
1

的提示是:JAVA:密碼標準

寫Java程序在命令行中讀取來自用戶的字符串(密碼),然後檢查密碼符合公司的密碼策略。

策略是:

1)密碼必須至少8個字符

2)密碼必須包含一個大寫字母

3)密碼必須包含一個數位。

使用while循環步驟通過串。

輸出「密碼OK」如果密碼相符,否則

輸出「密碼不符合政策。」

我有這樣下來,這似乎不是還在正常工作:

String password = ""; 
    boolean hasDigitAndUpper = false; 
    boolean hasUpper = false; 
    int i = 0; 

    System.out.print("Please enter a password: "); 
    password = scnr.nextLine(); 

    if (Character.isUppercase(password.charAt(i))){ 
     if (Character.isUppercase(password.charAt(i))) { 
      i++; 
      hasDigitAndUpper = true; 
     } 
    } 

    while (password.length() < 8 || hasDigitAndUpper != true) { 
     System.out.println("Password does not conform to policy"); 
     System.out.print("Please enter a password: "); 
     password = scnr.nextLine(); 
    } 
    System.out.println("Password OK"); 

我想我最大的問題是我的布爾值,我無法弄清楚如何解決。

+0

彈出的東西:一旦你得到一個新的密碼,你不要重新編譯hasDigitAndUpper。 Java不會自動讓它保持最新狀態。 – yshavit

+0

啊。我對編碼相當陌生,所以我不知道這一點。謝謝yshavit! GhostCat:我一整天都在工作和上課,現在就回到這個問題。大聲笑。 – Gene

回答

0

只是一些提示:

if (Character.isUppercase(password.charAt(i))){ 
    if (Character.isUppercase(password.charAt(i))) { 
     i++; 
     hasDigitAndUpper = true; 
    } 
} 

再往下,您使用的是while循環。所以你之前聽說過循環。提示:要爲循環整個字符串,並檢查所有字符。在我的密碼,大寫字符通常交替上升後來落後指數爲0或1

然後:

while (password.length() < 8 || hasDigitAndUpper != true) { 
    System.out.println("Password does not conform to policy"); 
    System.out.print("Please enter a password: "); 
    password = scnr.nextLine(); 
} 

不會做任何合理的。你想要的循環周圍的其他代碼。此代碼只是循環,並要求用戶輸入有8個字符新密碼 - 其他布爾hasDigitAndUpper值。

所以:你想寫一個小方法標準;然後你的代碼都:

while (not-all-criteria) { 
    password = new user input 
    check password length 
    check password has upper case 
    ... 

希望這是足以讓你去,請理解,我不會做你的功課你。你迫切需要自己練習這些東西!

0

你可以使用這個簡單的功能。這將迭代密碼並檢查條件。如果所有條件都滿足,則它返回true,否則爲false。

public static boolean isValid(String pwd) 
{ 
    if (pwd == null || pwd.length() < 8) 
    { 
     return false; 
    } 
    boolean containUpper = false; 
    boolean containDigit = false; 
    int i = 0; 
    while (i < pwd.length()) 
    { 
     if (containDigit && containUpper) 
     { 
      break; 
     } 
     if (Character.isUpperCase(pwd.charAt(i))) 
     { 
      containUpper = true; 
     } 
     if (Character.isDigit(pwd.charAt(i))) 
     { 
      containDigit = true; 
     } 
     i++; 
    } 
    return containDigit & containUpper; 
}