I'm a beginner in java and I have a problem. Why is " Password does not meet requirement: must contain only letters and digits" printing out two times? If the user puts Test## for example, the output above prints twice. When I put a password such as "asd" the error message "Password does not meet requirement: must be between 6 and 15 characters", only prints once. Which is what I want the second case to do. This is my code below, please feel free to tell me the issue. Thank you!
public static void main(String[] args) {
// User input
Scanner input = new Scanner(System.in);
// Variables
final String previousPassword1 = "secret007";
final String previousPassword2 = "your2eyes";
int amountofAttempts = 0;
boolean validPassword = false;
final int minLength = 6;
final int maxLength = 15;
while (!validPassword && amountofAttempts < 4) {
amountofAttempts++;
String yolo = getNewPassword(input);
if (!lengthTest(yolo)) {
printErrorMessage(1);
} else if (onlyLettersAndDigitsTest(yolo, yolo));
printErrorMessage(2);
}
}
public static String getNewPassword(Scanner input) {
System.out.println();
System.out.println();
System.out.print("Enter a password: ");
String passWord = input.nextLine();
return passWord;
}
public static boolean lengthTest(String length) {
boolean validLength = false;
if (length.length() >= 6 && length.length() < 15) {
validLength = true;
}
return validLength;
}
public static boolean onlyLettersAndDigitsTest(String digandlet, String length) {
for (int i = 0; i < length.length(); i++) {
if (Character.isLetterOrDigit(digandlet.charAt(i))) {
return false;
}
}
return true;
}
public static boolean containsOneToThreeDigitsTest(String password) {
int amountOfDigits = 0;
for (int i = 0; i < password.length(); i++) {
if (Character.isDigit(password.charAt(i))) {
amountOfDigits++;
}
}
if (amountOfDigits > 3 || amountOfDigits < 1) {
return false;
}
return true;
}
public static boolean differentThanLastTwoPasswordsTest(String previousPassword1, String previousPassword2, String password) {
if (password.equals(previousPassword1) || password.equals(previousPassword2)) {
return false;
} else {
return true;
}
}
public static void printErrorMessage(int errorCode) {
switch (errorCode) {
case 1:
System.out.print("Password does not meet requirement: must be between 6 and 15 characters");
break;
case 2:
System.out.print("Password does not meet requirement: must contain only letters and digits");
case 3:
System.out.print("Password does not meet requirement: must contain at least 1 digit and not more than 3");
break;
case 4:
System.out.print("Password does not meet requirement: must be different than previous 2 passwords");
break;
}
}
}