简体   繁体   中英

Boolean return; don't know how to return result I want

I'm working on a PW verification. I found a code developed by another user here and am using it (user: Quirliom). My problem is if the PW meets all requirements, it spits 1: PW verified. If not, it spits -1: PW not verified. In the boolean method using the code, if I state return true, whether the PW entered by user meets requirement of not, it will state PW meets requirement. How can I change it so if it meets requirement, true will come and if not, it will be false?

import java.util.*;
import java.lang.String;
import java.lang.Character;

public class Password {
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    System.out.print("Enter password: ");
    String password = input.next();
    if (isValid(password)) {
        System.out.println("1: Valid Password");
    } else {
        System.out.println("-1: Invalid Password");
    }
}


//Invoke method for PW verification
public static boolean isValid(String password) {

    //Checks if PW is at least 8 characters
    boolean isAtLeast8 = password.length() >= 8;//Checks for at least 8 characters
    if(!isAtLeast8)System.out.println("Must be 8 or more characters.");

    //PW cannot exceed 24 characters
    boolean isAtLeast24 = password.length() <= 24;
    if(!isAtLeast24)System.out.println("Must not exceed 24 characters.");

    //Checks if PW is only letters and digits - no special characters
    //Checks at least one char is not alpha numeric
    boolean hasSpecial = !password.matches(".*[!@#$%^&*].*");
    if(!hasSpecial)System.out.println("Must not contain special character !@#$%^&*.");

    //Check PW to have 2 uppercase
    boolean hasUppercase = !password.equals(password.toLowerCase());
    if(!hasUppercase)System.out.println("Must have 2 uppercase Character");

    //Check PW to have 2 lowercase
    boolean hasLowercase = !password.equals(password.toUpperCase());
    if(!hasLowercase)System.out.println("Must have 2 lowercase Character");

    //Check PW to have 2 digits
    boolean hasNumber = password.matches(".*\\d.*");
    if(!hasNumber)System.out.println("Must have 2 digits");

return true;

}

}

看起来您想要这样:

return isAtLeast8 && isAtLeast24 && hasSpecial && hasUppercase && hasLowercase && hasNumber;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM