[英]Char Array Values Not Holding User Input Values in JAVA
我定義了一個字符數組,它的值等於用戶從控制台輸入的值。 為了測試這是否正常工作,我打印出字符數組中的每個值並查看它是否正確。
char[] userPass = console.readPassword("🔒 Please enter your current password: ");
char[] newPass, newPassConfirmation; //Character arrays to store new password attempts:
if (Arrays.equals(map.get(currentUser).toCharArray(), userPass)) { //If password is correct, allow user to prcoceed:
boolean containsIllegal;
boolean passwordsMatch = false; //See if new password and new confirmation passwords match
/*
1. Get the first new password attempt and store it in a character array.
2. Then get the password confirmation attempt and store it in a character array.
3. Compare the passwords and see if they match.
*/
do{
do {
newPass = console.readPassword("🔑 Please enter your new password: ");
for(int i = 0; i < newPass.length; i++) {
//bw.write((char) newPass[i]);
System.out.print(newPass[i]);
};
containsIllegal = isValid(newPass);
} while (containsIllegal);
for(int i = 0; i < newPass.length; i++) {
//bw.write((char) newPass[i]);
System.out.print(newPass[i]);
};
do {
newPassConfirmation = console.readPassword("🔑 Please confirm your new password by entering it again: ");
containsIllegal = isValid(newPassConfirmation);
}while(containsIllegal);
if(Arrays.equals(newPass, newPassConfirmation)) {
passwordsMatch = true;
}
}while(!passwordsMatch);
在 do-while 循環中,值正確打印出來。 如果用戶輸入了“FISH”,則 for 循環打印出 FISH;
do {
newPass = console.readPassword("🔑 Please enter your new password: ");
for(int i = 0; i < newPass.length; i++) {
//bw.write((char) newPass[i]);
System.out.print(newPass[i]);
};
containsIllegal = isValid(newPass);
} while (containsIllegal);
問題是當我嘗試在 do-while 循環之外打印出 char 數組時。 我沒有結果。 如果用戶輸入 FISH 輸出是什么,還是一個空字符數組?
for(int i = 0; i < newPass.length; i++) {
//bw.write((char) newPass[i]);
System.out.print(newPass[i]);
}
為什么我的 do while 循環沒有改變字符數組的元素?
這是isValid
抱歉,這里是isValid
函數:
static boolean isValid(char[] userInput) {
for(int i=0; i<userInput.length; i++) {
if(userInput[i] == ':'){
System.out.println("\n🤮 You can not enter ':' please try again.");
Arrays.fill(userInput, (char) 0);
return true;
}
}
Arrays.fill(userInput, (char) 0);
return false;
}
newPass
數組的引用傳遞給isValid
,因此當您執行以下操作時:
Arrays.fill(userInput, (char) 0);
您正在用 0 填充newPass
。 由於無論密碼是否有效,您都在執行此操作,因此在調用isValid
后數組將始終為 0。 當您打印全零字符數組時,不會打印任何內容,因為 0 是 NULL 字符。
我認為Arrays.fill
調用在isValid
沒有任何作用。 isValid
根本不應該改變傳入的數組。
static boolean isValid(char[] userInput) {
for(int i=0; i<userInput.length; i++) {
if(userInput[i] == ':'){
System.out.println("\n🤮 You can not enter ':' please try again.");
return true;
}
}
return false;
}
valid.此外,它看起來像isValid
將返回密碼有效。 你可能應該重命名...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.