问题
I have an assignment that requires me to create a password checking program.
The password must be at least 8 characters, contain both capital and lower case letters, a digit and a special character.
I believe I am close to solving this problem but my skills are still developing and I've hit a wall.
package project1;
/**
*
* @author danechristian
*/
import java.util.*;
public class Project1
{
static Scanner console = new Scanner(System.in);
static final String SPECIAL_CHARACTERS = "!,#,$,%,^,&,*,|";
static String password;
public static void main(String[] args)
{
System.out.println("Create a password: ");
password = console.next();
if (validPassword(password))
{
System.out.println("Password Saved");
}
else
{
System.out.println("Invalid Passowrd. Password "
+ "must contain atleast 1 capital letter"
+ "1 lower case letter, 1 digit, 1"
+ "special character (!#$%^&*|) and "
+ "be atleast 8 characters long");
}
}
public static boolean validPassword(String password)
{
boolean upCase = false;
boolean loCase = false;
boolean isDigit = false;
boolean spChar = false;
if (password.length() >= 8)
{
for (int i = 0; i < password.length() - 1; i++)
{
if (Character.isUpperCase(password.charAt(i)))
{
upCase = true;
}
if (Character.isLowerCase(password.charAt(i)))
{
loCase = true;
}
if (Character.isDigit(password.charAt(i)))
{
isDigit = true;
}
if (SPECIAL_CHARACTERS.contains(password))
{
spChar = true;
}
}
}
return (upCase && loCase && isDigit && spChar);
}
}
回答1:
In order to check have something like this:
public static boolean validPassword(String password){
boolean upCase = false;
boolean loCase = false;
boolean isDigit = false;
boolean spChar = false;
if (password.length()>7){
if (password.matches(".+[A-Z].+")){
upCase = true;
}
if (password.matches(".+[a-z].+")){
loCase = true;
}
if (password.matches(".+[1-9].+")){
isDigit = true;
}
if (SPECIAL_CHARACTERS.contains(password)){
spChar = true;
}
}
return (upCase && loCase && isDigit && spChar);
}
回答2:
solved by changing
if (SPECIAL_CHARACTERS.contains(password)){ spChar = true;
to
if (SPECIAL_CHARACTERS.contains(password.substring(i,i+1))){ spChar = true;
this checks for the string within the string.
also, I removed the "- 1" from my for statement so that the bounds were corrects. also removed the commas from the SPECIAL_CHARACTERS constant.
the program now runs without issue, thanks for the advice everyone.
来源:https://stackoverflow.com/questions/33965542/password-check-program-checking-capitals-lowercase-letters-digit-and-special