我创建了一个从互联网上检索到的ArrayList
个常用密码,并初始化了一个名为commonPasswords
的数组。我想检查用户输入的密码是否与阵列中的任何密码匹配。但是,这似乎不起作用。我不知道为什么。任何帮助将不胜感激。
我刚开始学习如何编程,所以我在该领域相当新手。谢谢!
int commonpass = 0;
int check = 0;
while (commonpass == 0) {
if (password.equals(commonPasswords.get(check))) {
score = 0;
}
check++;
if (check >= commonPasswords.size()) {
commonpass++;
}
}
答案 0 :(得分:2)
改为使用List#contains
,例如
if(commonPasswords.contains(password)){
System.out.println("Password is not safe");
}
答案 1 :(得分:2)
使用Java 8,您可以按照以下方式执行
List<String> commonPasswords = Arrays.asList("A", "B", "C");
return commonPasswords.stream().anyMatch(str -> str.equals(password));
答案 2 :(得分:2)
正如钱德勒所说,你应该使用commonPasswords.contains(str)
代替password.equals(commonPasswords.get(check))
if commonPasswords.contains(password)
return true;
或者
return commonPasswords.contains(passwords);
答案 3 :(得分:0)
因为你是初学者,所以我为你演示了以下代码,展示了4种可能非常简单的方法来做你想做的事情。 建议初学者不要使用Java 8 Stream API和Lambda表达式。
List<String> commonPasswords = Arrays.asList("touraj", "ttt", "toraj", "123");
String userPassword = "123";
//First Way:
if (commonPasswords. contains(userPassword)) {
System.out.println("Password Found");
} else
{
System.out.println("Password Not Found");
}
//Second Way: foreach :: not suggested for beginners
for (String commonPassword : commonPasswords) {
if (commonPassword.equals(userPassword)) {
System.out.println("Password Found");
// here i use break after finding password to exit loop in order to not wasting cpu
break;
}
}
//Third Way: simple for loop :: suggested for beginners
for (int i = 0; i <commonPasswords.size() ; i++) {
if (commonPasswords.get(i).equals(userPassword)) {
System.out.println("Password Found");
}
}
//Forth way: Using Java 8 Stream Api :: Not Suggested for beginners like you
boolean isPassFound = commonPasswords.stream().anyMatch(pass -> pass.equals(userPassword));
if (isPassFound) {
System.out.println("Password Found.");
}
注意:为了理解我在这里建议的java 8代码,你首先需要学习面向对象和接口,然后学习匿名方法然后学习lambda表达式然后学习Stream API ...但我认为java 8版本是自我的解释和类似于人类语言。
答案 4 :(得分:0)
OP说他想要check to see if the user inputted password matches
所以我认为他们的意思是相同的。
如果OP确实在寻找相同的条目,那么OP应该使用String.equals
而不是Array.contains
。因为Array.contains
可能会给他一个假阳性结果。
private void checkPasswordExists(){
List<String> passwordList = Arrays.asList("pass1", "pass2", "pass12", "pass123");
int countContains = 0;
String userPassword = "pass1";
for(String password : passwordList){
if(password.contains(userPassword)){
countContains++;
}
}
int countEquals = 0;
for(String password : passwordList){
if(password.equals(userPassword)){
countEquals++;
}
}
System.out.println("Password countContains = " + countContains);
System.out.println("Password countEquals = " + countEquals);
}
以上代码写入控制台:
Password countContains = 3
Password countEquals = 1