I have java code for entering a password following certain rules

2.2k Views Asked by At

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:

  1. A password must have at least eight characters
  2. A password consists of only letters and digits
  3. 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;

  }
   }
1

There are 1 best solutions below

0
On

The error is here:

if (password.length() >=8 ){
    return false;
}

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:

if (password.length() < 8 ){
    return false;
} 

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:

    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;
        }
        if ((Character.isDigit(password.charAt(i)))) {
            countDigit = countDigit + 1;
        }
    }
    if (countDigit >= 2) {
        return true;
    } else {
        return false;
    }