我目前正在研究我的Java類的最終項目,我需要一點幫助!所以首先我要告訴你的指示,我的代碼,然後是我的問題。密碼驗證程序Java
說明
- 編寫提示用戶輸入密碼的程序。
- 創建一個名爲valid的布爾變量並將其設置爲true。如果以下任何測試失敗,請將其設置爲true。
- 檢查密碼,看它是否至少有8個字符。如果沒有,則顯示消息「密碼必須至少包含8個字符」
檢查密碼以查看它是否僅包含字母和數字。爲此,您需要遍歷字符串中的所有字符。角色C是數字信如果此表達式爲真:
( 'A' < = C & &Ç< = 'Z')|| ('A'< = c & & c < ='Z')|| ( '0' < = C & &Ç< = '9')
,如果這是即使不是真的,從你的循環打破並顯示信息, 「密碼必須只包含字母和數字」 5.如果程序結束時仍然有效,請顯示消息「密碼已接受!」。
我的代碼
import java.util.Scanner;
public class PasswordVerification {
public static void main(String[] args) {
// Creates a scanner
Scanner sc = new Scanner(System.in);
boolean valid = false;
String password;
// Asks user to enter password
System.out.print("Please enter password and then hit enter:");
password = sc.nextLine();
// Checks to see if password is at least 8 characters.
if (password.length()<8)
{
valid = false;
System.out.println("Password must have at least 8 characters");
}
// Checks each character to see if it is acceptable.
for (int i = 0; i < password.length(); i++){
char c = password.charAt(i);
if ( ('a' <= c && c <= 'z') // Checks if it is a lower case letter
|| ('A' <= c && c <= 'Z') //Checks if it is an upper case letter
|| ('0' <= c && c <= '9') //Checks to see if it is a digit
)
{
valid = true;
}
else
{
// tells the user that only letters & digits are allowed
System.out.println("Only letter & digits are acceptable.");
valid = false;
break;
}
}
// if the password is valid, tell the user it's accepted
System.out.println("Password Accepted");
}
}
因此,有說明書和我的代碼,我到目前爲止。我接近完成我只是在第四部分遇到問題。因此,預期輸出應該是:
Please enter a password: abc
Password much have at least 8 characters
Please enter a password: abcd1234$
Password must only contain letter and digits
Please enter a password: ####
Password must have at least 8 characters
Password must only contain letters and digits
Please enter a password: abcd1234
Password accepted!
當我鍵入ABC,這是我所得到的:
Please enter password and then hit enter:abc
Password must have at least 8 characters
Password Accepted
當我做這個節目結束!有人可以幫我解決這個問題嗎?先謝謝了。 =)另外,這是一個Java編程I類。
正則表達式可能是第4部分非常有幫助。有沒有理由不使用它?示例:http://stackoverflow.com/questions/11241690/regex-for-checking-if-a-string-is-strictly-alphanumeric – Joe
你需要添加一個循環,一個ex爲ex,並且所有的時間都在那裏直到密碼有效 – cralfaro
@joe海報顯然是一個完整的新手。正則表達式是稍後要解決的問題。 – slim