I am trying to make a simple password checker program in Java that checks a bunch of things about the user's password before allowing them to continue.
One of the thngs it checks for is making sure there is at least one capital letter in the passcode. Here is the code, first, the method that is used:
public static boolean checkString(String str) {
char ch;
boolean capitalFlag = false;
for(int i=0;i < str.length();i++) {
ch = str.charAt(i);
capitalFlag = Character.isUpperCase(ch);
}
return capitalFlag;
}
Then, the else if statement that checks this:
else if (!checkString(enterPasswordAgain) || !checkString(enterPasswordAgain)){
btnSubmit.setForeground(Color.RED);
btnSubmit.setText("Make sure your password has at least one capital letter.");
System.out.println("false");
}
else {
btnSubmit.setForeground(Color.GREEN);
btnSubmit.setText("Excellent password!");
System.out.println("true");
}
This returns false every time for some reason, despite the fact that this is the final thing checked and shouldn't cause any issues. I am very new to Java, could someone explain why this is not working? Thank you!
Tldr: Returns false every time despite being supposed to return whatever the value of capitalFlag is
The problem is that you are only returning the status of the last character. Try it like this.
public static boolean checkString(String str) {
for(char ch : str.toCharArray()) {
if (Character.isUpperCase(ch)) {
return true;
}
}
return false;
}
You may want to rename this method to containsUpperCase()