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
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