Check if an element of an array exists in another array (JAVA) -


how check if string inside of array of string? (java)

the user should able enter colour , program should check if inputted colour inside array or not.

for example:

user inputs: black

the program checks if colour black inside array of colours

program outputs: black

else

prorgam outputs: sorry mate, black isn't recognised.

commands[] parametrized array. if user types "circle colour black", circle gets stored in array location [0], colour gets stored in array location [1] , black gets stored in location [2] , on...

private string[] colours = {"black", "blue", "green", "magenta", "red", "white", "yellow"};   /**  * checks if typed in colour valid.  */ public void checkcolour(string[] commands) {     string varifiedcolour = null;      if(commands[1].equals("colour")){         for(int = 0; < colours.length; i++){             if(commands[2].contains(colours[i])){                 varifiedcolour = colours[i];                  //prints varifiedcolour check if method works.                 system.out.println(varifiedcolour);             }         }     } } 

i didn't find wrong code believe having problems checkcolour() method arguments. method consists of 1 parameter (not 3 seem think), command parameter requires string array passed it.

this therefore means whatever input may user (you don't show part of code) must 'split' using string.split() method place input string array. way input broken array elements want. string array passed argument checkcolour() method, example:

if user input (perhaps console input) string this: "circle colour black" must placed string array this:

string[] userinput.split(" "); 

now string array passed checkcolour() method this:

checkcolour(userinput); 

within checkcolour() method want change 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 not choice here since if user supplies colour of let's "gray" both colour "gray" , "lightgray" prove true if-then statement since string "gray" indeed contained within the string "lightgray". want more precise therefore use string.equals() method instead.

you notice i've added string.tolowercase() method conditional statement within if-then. ensures regardless of letter case user has supplied colour compared contained within colours[] string array if there letter case differences within colours[] array itself.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -