2017-06-18 83 views
0

我已經寫了一些代碼,但我似乎無法弄清楚如何獲取字符,數字或符號的確切數量。我固定了我的代碼,但它不起作用,我不知道爲什麼。提示用戶輸入與特定模式匹配的密碼

我的要求是

寫,提示用戶輸入匹配特定模式的密碼的Java程序。你的程序必須批准該用戶的條目。這裏是模式,順序如下:

-1 or more upper case letters 
-two lower case letters 
-1 or 2 digits 
-zero or 1 upper case letters 
-any two of this group @#$%^& 

我的代碼:

import java.util.Scanner; 
public class TestingCenter { 

public static void main(String[] args) { 
    int digit=0; 
    int special=0; 
    int upCount=0; 
    int upCount2=0; 
    int loCount=0; 
    String password; 
    Scanner scan = new Scanner(System.in); 
    System.out.println(" Enter Your Password:"); 
    password = scan.nextLine(); 

    for(int i =0;i<password.length();i++){ 
     char c = password.charAt(i); 
     if(Character.isUpperCase(c)){ 
      upCount++; 
    } 
     if(Character.isLowerCase(c)){ 
      loCount++; 
    } 
     if(Character.isDigit(c)){ 
      digit++; 
    } 
     if(Character.isUpperCase(c)){ 
      upCount2++; 
    } 
     if(c>=33&&c<=46||c==64){ 
      special++; 
    } 
} 
     if(special==2&&loCount==2&&upCount>=1&&(digit==1||digit==2)&&upCount2<=1){ 
     System.out.println(" Password is good:"); 
    } 
} 
} 
+0

哪部分指示要求你計算什麼? –

+0

「1或2位數字」:「數字> = 1」是否真的捕獲了? 「這個小組中的任何兩個@ @ $%^&」 – Henry

+0

「兩個小寫字母」應該是「兩個或多個小寫字母」還是「正好兩個小寫字母」? –

回答

1

如果我理解正確的話,順序字面意思是給定的順序。

如果是這樣的話,你想要正則表達式。忘記計數字符。

  • 1個以上大寫字母[A-Z]+
  • 2個小寫字母[a-z]{2}
  • 1或2位數\d{1,2}
  • 零或1大寫字母[A-Z]?
  • 該組@#$中的任意兩個%^ & [@#$%^&]{2}

所以,

Scanner scan = new Scanner(System.in); 
System.out.println(" Enter Your Password:"); 
String password = scan.nextLine(); 
System.out.println(password.matches("[A-Z]+[a-z]{2}\\d{1,2}[A-Z]?[@#$%^&]{2}"); 

如果這不符合您的指示,請檢查您的條件。顯然不是所有的東西都應該是>= 1

+2

我會認爲「這個組@@ $%^&中的任何兩個都意味着沒有重複」 –

+1

重複不是指定。兩個相同的字符被認爲是「任意兩個」 –

+0

也許,但從規範中不清楚它的含義,所以我認爲邁克爾需要澄清這一點。 –