johncho316
johncho316

Reputation: 21

Password Check Efficiency

My Java program checks if a user generated string is a valid password based on following rules:

  1. number of chars must be in [6, 10]
  2. there must be >= 1 char in the range ['a', 'z']
  3. there must be >= 1 char in the range ['A', 'Z']
  4. there must be >= 1 char in the range ['0', '9']

I have finished the program but I believe my method is too inefficient. Any thoughts?

import java.util.*;
public class Password {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter Password: ");
String pw = input.next();
boolean validPW = passwordCheck(pw);
if(validPW)
    System.out.println(pw + " is a valid password!");
else
    System.out.println(pw + " is not a valid password!");
}

public static boolean passwordCheck(String pw) {

boolean pwLength = false,
            pwLowerCase = false,
            pwUpperCase = false,
            pwNumCount = false;

int pwCharCount = pw.length();

if(pwCharCount >= 6 && pwCharCount <= 10)
        pwLength = true;

for(int position = 0; position < pwCharCount; ++position)
{
    if((pw.charAt(position) >= 'a') && (pw.charAt(position) <= 'z'))
        pwLowerCase = true;
}

for(int position = 0; position < pwCharCount; ++position)
{
    if((pw.charAt(position) >= 'A') && (pw.charAt(position) <= 'Z'))
        pwUpperCase = true;
}

for(int position = 0; position < pwCharCount; ++position)
{
    if((pw.charAt(position) >= '1') && (pw.charAt(position) <= '9'))
        pwNumCount = true;
}

if(pwLength && pwLowerCase && pwUpperCase && pwNumCount)
    return true;
else
    return false;

}

}

Upvotes: 1

Views: 68

Answers (1)

janos
janos

Reputation: 124656

I have finished the program but I believe my method is too inefficient. Any thoughts?

A bit, yes. First, you don't need the pwLength variable. You could return false immediately when a required condition doesn't match:

if (pwCharCount < 6 || pwCharCount > 10) return false;

Then, instead of iterating over the input multiple times, you could do it in a single pass. And since a character won't be at the same time uppercase, and lowercase, and numeric, you can chain those conditions together using else if, further reducing unnecessary operations.

for (int position = 0; position < pwCharCount; ++position) {
  char c = pw.charAt(position);
  if ('a' <= c && c <= 'z')) {
    pwLowerCase = true;
  } else if ('A' <= c && c <= 'Z') {
    pwUpperCase = true;
  } else if ('0' <= c && c <= '9') {
    pwNumCount = true;
  }
}

The final condition can be simpler, returning the result of the boolean condition directly:

return pwLowerCase && pwUpperCase && pwNumCount;

Upvotes: 3

Related Questions