Chan Guevarra Chan Guevarra - 1 month ago 6
Java Question

The password validation sends out the wrong output?

The program that I've written is giving me the wrong output. It verifies whether the input password is 6 characters long with letters and numbers, if one of the requirement is not met, then it should say "Invalid Password." Otherwise, then it should output "Password Accepted." But when I enter more than 6 character long password, though the password is all letters, it still say password accepted.

import java.util.*;
public class passwd {
public static void main(String[] args)
{
String in_pass;
int i = 0, x = 0, l = 0, d = 0;
boolean valid_len;
Scanner in = new Scanner(System.in);
System.out.print("Enter Password: ");
in_pass = in.next();
int len = in_pass.length();
valid_len = (len >= 6) ? true : false;
char passwd_l;
char passwd_d;
if (valid_len == false)
{
System.out.println("Invalid Password");
}
else if (valid_len == true)
{
for (i = 0, x = 0; i < len; i++, x++)
{
passwd_l = in_pass.charAt(i);
if (Character.isLetter(passwd_l))
{
l += i;
}
passwd_d = in_pass.charAt(x);
if (Character.isDigit(passwd_d))
{
d += x;
}
}
}
if (i > 0 && x > 0)
{
System.out.println("Password Accepted");
}
}
}

Answer

Check out this one!

else if (valid_len == true){
       for (i = 0; i < len; i++){
              passwd_l = in_pass.charAt(i);
              if (Character.isLetter(passwd_l))
              {
                    l ++;
              }
              if (Character.isDigit(passwd_l))
              {
                    d ++;
              }
       }
} 
if (l > 0 && d > 0){
       System.out.println("Password Accepted");
} 
Comments