我正在尝试制作一个从用户输入中检查密码的程序。密码标准是至少有 10 个字符,其中至少 1 是数字,1 是小写字母,1 是大写字母。对于作业,我必须创建一个自定义异常类,这是下面的第一个。然后,我必须在第二个类中创建一个方法,该方法检查每个条件并使用正确的错误消息引发异常。我已经尝试了几个小时,但由于某种原因,我的程序根本不会打印任何东西,我希望一双新的眼睛可以帮助我指出正确的方向。我不是在寻找讲义,我只是对自定义异常的掌握非常薄弱(我已经阅读了 API,我的课本以及每天都去上课,所以并不是我没有尝试。)
public class PasswordException extends Exception {
public PasswordException() {
super("Invalid Password: ");
}
public PasswordException(String problem) {
super("Invalid: " + problem );
}
}
import java.util.Scanner;
public class passwordMaker{
public static boolean validPassword(String passwordIn) throws PasswordException {
boolean lengthCheck = false;
boolean upperCheck = false;
boolean lowerCheck = false;
boolean digitCheck = false;
boolean check = false;
boolean keepGoing = true;
String problem;
for(int i=0;i<passwordIn.length();i++) // This loop tests string
{
char s=passwordIn.charAt(i); // char s represents the index
if(Character.isUpperCase(s)) // This verifies there is a uppercase letter
{
upperCheck = true;
}
if(Character.isLowerCase(s)) // This verifies there is a lowercase letter
{
lowerCheck=true;
}
if(Character.isDigit(s)) // This verifies there is a digit
{
digitCheck = true;
}
if (passwordIn.length() >= 10) // This verifies the password is atleast 6 characters
{
lengthCheck = true;
}
}
do {
//extracts problem
if (upperCheck == false) {
problem = "The password does not have an upper case letter.";
keepGoing = false;
}
else if (lowerCheck == false) {
problem = "The password does not have a lower case letter.";
keepGoing = false;
}
else if (digitCheck == false) {
problem = "The password does not have a digit.";
keepGoing = false;
}
else if (lengthCheck == false) {
problem = "The password is not long enough";
keepGoing = false;
}
else {
problem = "nothing.";
keepGoing = false;
}
}while(keepGoing);
// Tests results of the loop
if(upperCheck == true && lowerCheck == true && digitCheck == true && lengthCheck == true)
{
check=true;
}
if (check = true) {
return true;
}
else {
throw new PasswordException("the password needs" + problem);
}
}
public static void main(String[] args) {
System.out.println("Enter a password.");
Scanner sc = new Scanner(System.in);
String password = sc.next();
try {
validPassword(password);
}
catch (PasswordException e) {
System.out.println(e.getMessage());
}
}
}
我尝试通过可视化工具运行它,但它会到达我应该输入内容的位置并显示 NoSuchElement 错误,而我的命令提示符没有,它在我输入密码后根本不会显示任何消息。