【发布时间】:2016-03-02 03:17:52
【问题描述】:
我有一个任务要求我创建一个密码检查程序。
密码必须至少为 8 个字符,包含大小写字母、数字和特殊字符。
我相信我已经接近解决这个问题了,但我的技能仍在发展中,我已经碰壁了。
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);
}
}
【问题讨论】:
-
你有什么问题?
-
你不能只使用正则表达式吗?
-
我不知道你在哪里碰到了这个问题,因为对我来说一切都很简单明了。因此,我无法看到您的问题。请解释它在哪里。
-
不计算大写字母小写字母数字或特殊字符。不熟悉正则表达式。
-
将密码存储在字符串中是不好的做法。应该使用 char[] 作为初学者。字符串是不可变的,这意味着当您完成密码时,密码将位于 RAM 中。