2016-05-26 33 views
1

我想讓程序做2件事:如何創建一個Java程序來檢查您的密碼是否強大?

  1. 檢查字符串(密碼輸入)是否包含字母和數字。
  2. 檢查密碼是否有至少8個字符。

這裏是我的代碼:

import java.util.*; 
class howstrong 
{ 
    public static void main(String ar[]) 
    { 
    String password; 
    int i; 
    int c=0; 
    Scanner in = new Scanner(System.in); 
    System.out.println("ENTER PASSWORD"); 
    password = in.next(); 
    if (password.length() <= 8) 
    { 
     for (i = 0; i <= password.length(); i++) 
     { 
     char x = password.charAt(i); 
     if (Character.isLetter(x)) 
     { 
      if (Character.isDigit(x)) 
      c = 1; 
     } 
     } 
     if (c == 1) 
     System.out.println("STRONG"); 
     else 
     System.out.println("NOT STRONG"); 
    } 
    else 
     System.out.println("HAVE AT LEAST 8 CHARACTERS"); 
    } 
} 
+0

格式化您的代碼 – garg10may

+0

格式化!請看看代碼! – shreydan

+0

你有特定的問題或錯誤? –

回答

2

你有幾個問題:

i <= password.length()應該i < password.length()

if (password.length() <= 8)應該if (password.length() >= 8)

要檢查如果字符是字母,並在同一時間的一個數字。

最後,我建議使用兩個標誌,一個用於檢測是否有字母,另一個用於檢測是否有數字。

全部放在一起:

import java.util.Scanner; 

class howstrong { 
    public static void main(final String ar[]) { 
     String password; 
     Scanner in = new Scanner(System.in); 
     System.out.println("ENTER PASSWORD"); 
     password = in.next(); 

     boolean hasLetter = false; 
     boolean hasDigit = false; 

     if (password.length() >= 8) { 
      for (int i = 0; i < password.length(); i++) { 
       char x = password.charAt(i); 
       if (Character.isLetter(x)) { 

        hasLetter = true; 
       } 

       else if (Character.isDigit(x)) { 

        hasDigit = true; 
       } 

       // no need to check further, break the loop 
       if(hasLetter && hasDigit){ 

        break; 
       } 

      } 
      if (hasLetter && hasDigit) { 
       System.out.println("STRONG"); 
      } else { 
       System.out.println("NOT STRONG"); 
      } 
     } else { 
      System.out.println("HAVE AT LEAST 8 CHARACTERS"); 
     } 
    } 
} 
+0

非常感謝您的回答。我使用c = 1作爲標誌,但它沒有像Julien Lopez指出的那樣工作。感謝你的回答! – shreydan

0

在你的循環,你檢查你的字符是字母一個數字。所以c永遠不會設置爲1.我建議你學會使用調試器,它會幫助你輕鬆解決這類錯誤。

+0

如何檢查字符串是否包含數字和字母? – shreydan

2

有一個正則表達式的表達,你可以用它來檢查密碼強度。 所以你調用的方法在你的代碼是這樣的::

password = in.next(); 

    if(isStrong(password){ 
     //good password, do stuff 
    } 
    else{ 
     //not so good, prompt again 
    } 

,並且該方法是這樣的:

private boolean isStrong(String password){ 
    return password.matches("^(?=.*[A-Z].*[A-Z])(?=.*[[email protected]#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z])"); 

    } 

下面是如果密碼相匹配的表達可以添加一個檢查驗證方法一個可以用來檢查密碼強度的正則表達式。

^(?=.*[A-Z].*[A-Z])(?=.*[[email protected]#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$ 

你可以看原來的帖子和選定的答案here

相關問題