Monday, May 21, 2018

java - How can I verify that an array of strings contain a certain string?




Given :



String[] directions = {"UP","DOWN","RIGHT","LEFT","up","down","right","left"};

String input = "Up";



How can I verify that an input from stdin is within the directions array or not ?



I can make a loop and check each item with input using equal ,but I'm looking for a more elegant way.



Regards,Ron


Answer



Convert the array of valid directions to a list:



List valid = Arrays.asList(directions)



Or just declare it directly as:



List valid = Arrays.asList("UP", "DOWN", "RIGHT", "LEFT", "up", "down", "right", "left")


You can then use the contains method:



if (valid.contains(input)) {
// is valid

} else {
// not valid
}


Note that this won't match a mixed case input such as "Up" so you might want to store just the uppercase values in the list and then use valid.contains(input.toUpperCase())


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...