35

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

1

5 Answers 5

62

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())

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

9 Comments

I'd prefer foreach on array, over creating new List just to iterate on it...
Question for everybody - anybody have any idea why Java doesn't have an Arrays.indexOf() method? (to parallel List.indexOf()). Since the array of Strings is usually some static final thing, I find the converting to a List very annoying, so I usually write my own little linear search utility.
@user949300 - use ArrayList()
Mostly because generics and arrays don't get along. Avoid using arrays, use List.
Does not work. I created a 2D array in which every element is "EMPTY". Arrays.asList(array).contains("EMPTY") returns true until one element changes to something that isn't "EMPTY". Why? The array still contains "EMPTY".
|
6

Convert your array to a List and than use the contains method.

List mylist = Arrays.asList(directions);
mylist.contains(input);

The contains method returns:

true if the list contains the specified element.

Comments

3

Unfortunately, Java does not have an Arrays.indexOf() method. Your best bet is to write a little utility to do a simple linear search. Or you could convert to an ArrayList (see Arrays.asList()) and call indexOf() or contains().

If the array is large and speed is a concern, you could sort the array, and then use Arrays.binarySearch().

Comments

3

Use ArrayList instead and its contains method

Comments

0

Since we are specifically talking about arrays of strings, not just any array: another approach which solves the case-insensitivity question elegantly would be using regular expressions. Either through the Pattern class or the String's matches method.

if (input.matches("(?i)" + String.join("|", directions))) {
    // valid
}
else {
    // invalid
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.