'Answer consists out of certain characters
Scanner input = new Scanner(System.in);
String[] colors = {"R", "G", "B", "P", "O", "Y"};
String guess = "";
String valid = false;
//Get Input
guess = input.nextLine().toUpperCase();
// Change String Array to Regular String
String Colors = "";
for(int i=0; i<colors.length; i++) {
Colors += colors[i];
}
// See if Guess Consists out of Correct Letters
if(guess.matches(Colors)) {
valid = true;
}
Basically what I want to achieve with this code is to check if the input given meets the requirements.
In this case does guess only consists of the letters given in colors, for example:
if guess = RGB then valid = true
if guess = RGBA then valid = false
I know I can also put it in manually like this:
if(guess.matches("[RGBPOY]+")) {
valid = true;
}
But I want to keep it procedural.
Is there a way to get this working? Or am I better off using a different method like say a for loop?
I only recently started with JAVA and am not yet familiar with all the different approaches it has to offer.
Solution 1:[1]
try this:
valid = Arrays.asList(colors).contains(guess)
Solution 2:[2]
Stupid mistake on my part.
The code was in the right way, just overlooked some simple things
guess.matches("[RGBPOY]+") was the manual, working piece of code.
The string Colors just printed RGBPOY.
Meaning I missed a few things to get this to work.
By either doing this
Colors = "[" + Colors + "]+";
if(guess.matches("Colors")) {
}
or this
if(guess.matches("["+stringArray+"]+")) {
}
The code worked as if it was put in manually since both were [RGBPOY]+
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Federico klez Culloca |
| Solution 2 | Bram Vrielink |
