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

General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • Does this answer your question? [How do I determine whether an array contains a particular value in Java?](https://stackoverflow.com/questions/1128723/how-do-i-determine-whether-an-array-contains-a-particular-value-in-java) or [Finding if an array contains all elements in another array](https://stackoverflow.com/questions/16524709/finding-if-an-array-contains-all-elements-in-another-array) – jhamon May 12 '20 at 09:23
  • Your if-statement seems fine to me. – NomadMaker May 12 '20 at 09:26

2 Answers2

1

try this:

valid = Arrays.asList(colors).contains(guess)
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
slaidurch
  • 35
  • 5
  • 1
    If `guess = "GRB"` then `valid` would be `false`. (Note the permutation.) I've understood that this would be required, as well. – Dirk R May 12 '20 at 09:22
0

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