1

How to check if a String is inside of an array of String? (JAVA)

The user should be able to enter a colour and then the program should check if the inputted colour is inside the array or not.

For example:

USER INPUTS: black

The program checks if the colour black is inside an array of colours

PROGRAM OUTPUTS: black

else

PRORGAM OUTPUTS: Sorry mate, black isn't recognised.

commands[] is a parametrized array. If the user types "circle colour black", then circle gets stored in array location [0], colour gets stored in array location [1] and black gets stored in location [2] and so on...

private String[] colours = {"black", "blue", "green", "magenta", "red", "white", "yellow"};

 /**
 * Checks if the typed in colour is valid.
 */
public void checkColour(String[] commands)
{
    String varifiedColour = null;

    if(commands[1].equals("colour")){
        for(int i = 0; i < colours.length; i++){
            if(commands[2].contains(colours[i])){
                varifiedColour = colours[i];

                //Prints varifiedColour to check if this method works.
                System.out.println(varifiedColour);
            }
        }
    }
}
3
  • 2
    What problem you are facing (and please don't say "it doesn't work" - we know/assume that since otherwise you wouldn't be here - so try to be more specific). Commented Jan 16, 2016 at 18:07
  • So I'm using blues as my development environment and I get an error saying "java.lang.String cannot be coverted to java.lang.String[]" whenever I input a colour. I want to check if an array of Strings is inside of another array of Strings? I'm a beginner so I'm finding it hard to explain in "technical talk". Commented Jan 16, 2016 at 18:24
  • Please edit your question and put that error message you are getting there. Commented Jan 16, 2016 at 18:26

3 Answers 3

1

Why are you using String#contains? Your program should be as simple as

for (String color : colors) {
  if (color.equals(input)) {
    return true;
  }
}
return false;

Also, if this is not a toy program, be aware of spelling differences - so for example normalize both input and your colors to be lowercase and have no surrounding whitespace.

Sign up to request clarification or add additional context in comments.

4 Comments

No this isn't a play around/experimental program. Oh ok, so you mean by using the .trim() method and .toLowerCase() method from the java api?
The program must: "If the inputted colour has an exact character by character match of an element stored inside of an array, then change the object's colour to whatever the user inputted." So I can't see how returning true or false would achieve this? Do you have any advice on how I could change a objects colour by using true or false?
@ReeLink All requirements should be part of your original question. Don't post them only under some answers (you are limiting your chances of getting proper answer since not everyone willing to help you will also be willing to search for all requirements under different places than your post).
Oh ok, sorry, I'm new to programming and to using this website :/ I'll keep this in mind if I post future questions. Thank you for trying to help me @Pshemo
1

Try to use second for loop like this removing if like this:

   for(int i = 0; i < colours.length; i++){
         for(int j = 0; j < commands.length; j++){
        if(commands[j].contains(colours[i])){
            varifiedColour = colours[i];

            //Prints varifiedColour to check if this method works.
            System.out.println(varifiedColour);
        }
      }
  }

2 Comments

I'll give this a go. Thanks for your advice, i'll let you know how I get along.
The way you did it has worked! Thank you very much!
0

I personally didn't find anything wrong with your code but I believe you are having problems with your checkColour() method arguments. The method consists of one parameter (not three like seem to think), the command parameter obviously requires a String array to be passed to it.

This therefore means that whatever the input may be from your User (you don't show that part of your code) must be 'split' using the String.split() method so as to place that input into a String Array. This way the input will be broken up into the array elements as you want. Then that string array is passed as an argument to the checkColour() method, for example:

If the User input (perhaps from console input) is a string like this: "circle colour black" then it must be placed into a String Array like this:

String[] userInput.split(" ");

Now this String array is passed to the checkColour() method like this:

checkColour(userInput);

Within your checkColour() method you also want to change the if-then conditional statement from:

if(commands[2].contains(colours[i])){ ....

To this:

if(commands[2].toLowerCase().equals(colours[i].toLowerCase())){ ....

The String.contains() method is really not a good choice here since if a User supplies a colour of let's say "gray" then both the colour "gray" and "lightgray" will prove true to the if-then statement since the string "gray" is indeed contained within the the string "lightgray". You want to be more precise than this therefore use the String.equals() method instead.

You will also notice that I've added the String.toLowercase() method to the conditional statement within the if-then. This ensures that regardless of what letter case the user has supplied the colour with it will be compared properly with what is contained within the colours[] string array even if there are letter case differences within the colours[] array itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.