user7696912
user7696912

Reputation:

Program which prompts the user to enter a password and checks conditions

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!

Upvotes: 0

Views: 2974

Answers (1)

ElectronicManuel
ElectronicManuel

Reputation: 113

You could simply move your valid variable from the main method to the valid method and set it to false for every condition not met. Only return in the end after every condition has been checked.

public static boolean checkValid(String password) {
    boolean valid = true;

    if (password.length() < 8) {
        System.out.println("Password must have at least eight characters.");
        valid = false;
    }
    if(!password.matches("[0-9a-zA-Z]+")) {
        System.out.println("Password must only contain letters and digits.");
        valid = false;
    }

    return valid;
}

And you don't need to iterate through every character of the password to match the regex.

Upvotes: 1

Related Questions