how to use .contains to select certain letters of the alphabet

Viewed 309

I need the user input to:
- have no numbers
- be 4 characters long
- only use certain letters of the alphabet [R, B, G, P, Y, O]
I have figured out how to do no numbers and only 4 character length, however, I can't seem to figure out how to restrict certain letters of the alphabet (everything other than R, B, G, P, Y, O.)

        guess = input.nextLine();
        guess = guess.toUpperCase();
        while (guess.length() != 4 || guess.contains("[0-9]") || guess.contains("[ACDEFHIJKLMNQSTUVWXZ]")) {
            System.out.println("Bad input! Try again");
            System.out.println("Use the form \"BGRY\"");
            guess = input.nextLine();
        }

This is the code I have so far, it doesn't seem to work

2 Answers

Do it as follows:

while(!guess.matches("[RBGPYO]{4}")) {
    // ...
}

Demo:

public class Main {
    public static void main(String s[]) {
        // Tests
        System.out.println(matches("RBGPYO"));
        System.out.println(matches("RBGP"));
        System.out.println(matches("R1BGP"));
        System.out.println(matches("ABCD"));
        System.out.println(matches("1234"));
        System.out.println(matches("BGPY"));
        System.out.println(matches("BYPG"));
    }

    static boolean matches(String input) {
        return input.matches("[RBGPYO]{4}");
    }
}

Output:

false
true
false
false
false
true
true

There are also a lot of ways without using Regex.

You cannot use String::contains in this case since this method works with a certain character sequence and your use-case is too specific. However, you can use the advantage of List::contains which might be more useful as long as the String is be understood as a List<Character> using :

List<Integer> characters = "RBGPYO".chars()
    .boxed()
    .collect(Collectors.toList());

boolean matches = guess.length() == 4 && 
    guess.toUpperCase().chars().allMatch(characters::contains);

If you are not a fan of this feature, a good old way for-loop:

List<Character> characters = Arrays.asList('R', 'B', 'G', 'P', 'Y', 'O');
boolean matches = guess.length() == 4;
if (matches) {
    for (char ch : guess.toUpperCase().toCharArray()) {
        if (!characters.contains(ch)) {
            matches = false;             
            break;                         // it's important to break the cycle
        }
    }
}

In any case, important is to check the length before you check the characters. This is valid as long as the guess should contain characters and to be of a certain length.

Related