所以我試圖讓這個把用戶輸入的字符串,並檢查密碼,以確保這兩個東西:Java的故障檢查,如果密碼字符串是有效的
- 密碼是最低的8個字符。
- 密碼只包含字母和數字。
現在的問題是這樣的: 檢查了至少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!");
}
}
任何幫助,在這一切將是偉大的。
這是否有幫助:http://stackoverflow.com/questions/13674449/checking-password-code? – ppasler
找到無效字符後,應將其設置爲false並跳出循環。否則,您可能會再次將標誌設置爲真。 –