[英]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.