2017-01-07 23 views
0

所以我試圖讓這個把用戶輸入的字符串,並檢查密碼,以確保這兩個東西:Java的故障檢查,如果密碼字符串是有效的

  1. 密碼是最低的8個字符。
  2. 密碼只包含字母和數字。

現在的問題是這樣的: 檢查了至少8個字符的工作密碼,但檢查它,以確保它僅包含字母和數字不起作用。如果輸入了最小數量的數字/字母,它只會在沒有給出單個消息的情況下終止。 但是,如果它看到一個字符不是字母或數字,它會打印出此

請輸入密碼:###

密碼只能包含字母和數字。

密碼只能包含字母和數字。

密碼只能包含字母和數字。

密碼接受!

輸出是它應該這樣:

請輸入密碼:###

密碼只能包含字母和數字。

請輸入密碼:test1234

密碼已被接受!

password.java  
    package Password; 
    import java.util.Scanner; 

    public class Password { 

    public static void main(String[]args) 
    { 

    Scanner input = new Scanner (System.in); 
    boolean valid = true; 
    System.out.println("Please enter a password:"); 
    String password = input.nextLine(); 
    int i = 0; 
    //declares i as the counter varible to control the loop and initializes it to 0 

    if((password.length() < 8)) //check the passwords length and make sure it's a minimum of 8 characters 
    { 
    System.out.println("Password must have at least 8 characters."); 
    valid = false; 
    } 
    //loops the code below it for the length of i until the password length is reached 
    while(i < password.length()) 
    { 
    if ((password.charAt(i)>='a' && password.charAt(i)<='z') || (password.charAt(i)>='A' && password.charAt(i)<='Z') ||(password.charAt(i)>='0' && password.charAt(i)<='9')) 
    //loop through all the characters in the string entered and make sure they only consist of letters and numbers 
     valid = true; 
    else 
    { 
     System.out.println("Password can only contain letters and numbers."); 
     valid = false; 
    } 
    i++; 
    //add an iteration to the loop 
    } 

    if(!valid == true) 
    System.out.println("Password accepted!"); 
    } 
    } 

任何幫助,在這一切將是偉大的。

+0

這是否有幫助:http://stackoverflow.com/questions/13674449/checking-password-code? – ppasler

+1

找到無效字符後,應將其設置爲false並跳出循環。否則,您可能會再次將標誌設置爲真。 –

回答

0

您可以簡化代碼,首先從valid開始檢查password.length();然後測試密碼中的每個字符(如果任何字符無效,則停止)。然後在顯示您接受的消息之前最後檢查密碼是否有效。像,

Scanner input = new Scanner(System.in); 
System.out.println("Please enter a password:"); 
String password = input.nextLine(); 
boolean valid = password.length() >= 8; 

if (!valid) { 
    System.out.println("Password must have at least 8 characters."); 
} else { 
    for (char ch : password.toCharArray()) { 
     if (!Character.isLetter(ch) && !Character.isDigit(ch)) { 
      System.out.println("Password can only contain letters and numbers."); 
      valid = false; 
      break; 
     } 
    } 
} 
if (valid) { 
    System.out.println("Password accepted!");   
} 
0

在此校驗碼的主要錯誤是while循環,當你看到一個錯誤的字符就沒有必要繼續循環,只要你做這種檢查的那樣:

String toCheck;  //the string to check some criteria 
boolean valid = true; // we assume that nothing wrong happen till now 

for(int i=0;i<toCheck.length();i++){ //loop over the characters 
    if(/*condition of wrong case*/){ 
     valid = false;    //mark that something wrong happen 
     break;      //exit the loop no need to continue 
    } 
} 

if(valid){ 
    //nothing wrong happen 
} else { 
    //something wrong happen 
}