Some websites impose certain rules for passwords. I am writing a method that checks whether a string is a valid password.
The rules of the password are:
- A password must have at least eight characters
- A password consists of only letters and digits
- A password must contain at least two digits
I figured out most of the code, I think I got some concept correct just right now no matter what password I enter it prints out "invalid password"..I tried running the debugger but got really confused.
This is my code below:
import java.util.Scanner;
public class practice {
public static void main(String[] args) {
System.out.print("Enter a password");
Scanner input = new Scanner(System.in);
String password = input.nextLine();
boolean isCorrect = checkPassword(password);
if(isCorrect)
{
System.out.println("Valid Password");
}
else
{
System.out.println("Invalid Password");
}
}
//this method checks the password
public static boolean checkPassword(String password)
{
int countDigit = 0;
if (password.length() >=8 ){
return false;
}
for(int i = 0; i <password.length(); i++)
{
if(!(Character.isLetterOrDigit(password.charAt(i))))
{
return false;
}
}
for(int i = 0; i<password.length(); i++){
if((Character.isDigit(password.charAt(i)))){
countDigit = countDigit + 1;
}
}
if (countDigit >= 2){
return true;
}
else
return false;
}
}
The error is here:
Here you say that if password is longer than or equal to 8 characters, the password is invalid, which is the complete opposite of the requirement. Change it to:
Also, you can reduce the number of for loops to make the code faster. You can count the number of digits and check
isLetterOrDigit
in the same for loop: