samiam0295
samiam0295

Reputation: 23

Is there a more efficient way to check characters in a string?

For this assignment, I need to accept a lock combination and check if:

I am wondering if there is a better way to do this than checking each position for a digit?

Scanner input = new Scanner(System.in);
String lockComb;
System.out.print("Please enter a lock combination ( ddRddLddR ): ");
lockComb = input.nextLine();

if((lockComb.length() == 9) && ((lockComb.charAt(2) == 'r') || (lockComb.charAt(2) == 'R')) && 
    ((lockComb.charAt(5) == 'l') || (lockComb.charAt(5) == 'L')) && ((lockComb.charAt(8) == 'r') 
        || (lockComb.charAt(8) == 'R')))
{
    if((Character.isDigit(lockComb.charAt(0))) && (Character.isDigit(lockComb.charAt(1))) && 
        (Character.isDigit(lockComb.charAt(3)) && (Character.isDigit(lockComb.charAt(4))) && 
            (Character.isDigit(lockComb.charAt(6))) && (Character.isDigit(lockComb.charAt(7)))))
    {
        System.out.println(lockComb + " is a valid lock combination!"); 
    }

    else
    {
        System.out.println(lockComb + " is not a valid lock combination!");
    }
}

else
{
    System.out.println(lockComb + " is not a valid lock combination!");
}

Upvotes: 2

Views: 113

Answers (2)

kasdega
kasdega

Reputation: 18776

How about just for fun a solution that doesn't involve regular expressions. I'm not arguing at all for or against just merely a different solution. One thing you do lose if using a regular expression is the ability to tell exactly why this is not a valid lock combination. It's up to you to figure out what the best solution is given the scenario you are coding for.

public static boolean matcher (String lockComb) {
    if(lockComb.length() != 9) {
        System.out.println(lockComb + " is not a valid lock combination!");
        return false;
    }
    boolean isValid = true;

    char[] comb = lockComb.toUpperCase().toCharArray();
    for (int i = 0; i < comb.length; i++) {
        switch (i) {
        case 2:
        case 8:
            isValid = (comb[i] == 'R');
            break;
        case 5:
            isValid = (comb[i] == 'L');
            break;
        default:
            isValid = Character.isDigit(comb[i]);
            break;
        }
        if(isValid == false) break;
    }
    if(isValid) {
        System.out.println(lockComb + " is a valid lock combination!");
    } else {
        System.out.println(lockComb + " is not a valid lock combination!");
    }

    return isValid;
}

Upvotes: 2

rgettman
rgettman

Reputation: 178253

To simplify things, you can use a regular expression:

if (lockComb.matches("[0-9][0-9][rR][0-9][0-9][lL][0-9][0-9][rR]")

(That's lowercase-l and uppercase-L in the middle.)

(No need to check the length, which is implicitly defined by the regular expression.)

Upvotes: 6

Related Questions