So I have been working on this program which prompts the user to enter a password but the password must be at least 8 characters long and only contain letters and digits. Here is my code:
import java.util.Scanner;
public class Password {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Please enter a password: ");
String password = input.nextLine();
boolean valid = true;
if (valid(password)) {
System.out.println("Password accepted!");
}
}
public static boolean valid(String password) {
if (password.length() < 8) {
System.out.println("Password must have at least eight
characters.");
return false;
} else {
char c;
for (int i = 0; i < password.length(); i++) {
c = password.charAt(i);
if (password.matches("[0-9a-zA-Z]+")) {
return true;
} else {
System.out.println("Password must only contain letters and digits.");
return false;
}
}
return true;
}
}
}
The problem I'm having is that when I enter an input like $$$, the only output is "Password must have at least eight characters", but I need both this output and ""Password must only contain letters and digits." In other words, I need the program to check if both conditions are false and display both outputs. How would I go about doing that?
Also, if you have any suggestions on how to make my program better, that would be helpful as well.
Thank you!
Aucun commentaire:
Enregistrer un commentaire