Wednesday, 16 March 2016

java - Find if a String is present in an array




OK let's say I have an array filled with {"tube", "are", "fun"} and then I have a JTextField and if I type either one of those commands to do something and if NOT to get like a message saying "Command not found".



I tried looking in Java docs but all I am getting is things that I don't want like questions and stuff... so, how is this done? I know there is a "in array" function but I'm not too good with combining the two together.



Thanks.



Here is what I have so far:



String[] dan = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};
boolean contains = dan.contains(say.getText());


but I am getting cannot find symbol in dan.contains


Answer



This is what you're looking for:



List dan = Arrays.asList("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue");

boolean contains = dan.contains(say.getText());


If you have a list of not repeated values, prefer using a Set which has the same contains method


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...