2

I am writing a method and would like to start the method with a comparison to see if a stored static string is equal to other words. Here it is in psuedocode:

While (String1 is neither equal to "A" nor "B" nor "C" nor "D")
{
    Print (Please enter a correct option);
    Take input;
}

Any help is great thanks.

2
  • 12
    Create a SET of of A, B, C, D and check set.contains(string1) in while loop Commented May 15, 2018 at 17:42
  • I would prefer to use a do while loop Commented May 15, 2018 at 17:48

4 Answers 4

3

In your case, you have four admissible inputs namely "A", "B", "C", "D". This can easily be implemented only using boolean operators; namely the loop condition is when your input is neither that of "A" nor "B" nor "C" nor "D".

Scanner input = new Scanner(System.in);

System.out.println("Enter a selection (NOR): ");
String string1 = input.next();

while (    !string1.equals("A")
        && !string1.equals("B") 
        && !string1.equals("C") 
        && !string1.equals("D")) {
    System.out.println("Enter again (NOR): ");
    string1 = input.next();
}
input.close();

But what about situations where there are arbitrarily but finitely many admissible inputs, such as having all letters of the Hungarian alphabet? The set may be the best option.

Scanner input = new Scanner(System.in);

// Either manually or use a method to add admissible values to the set
Set<String> admissible = new HashSet<String>();
admissible.add("A");
admissible.add("B");
admissible.add("C");
admissible.add("D");
// ... and so on. You can also use helper methods to generate the list of admissibles
// in case if it is in a file (such as a dictionary or list of words).

System.out.println("Enter a selection (Set): ");
String string1 = input.next();

// If input string1 is not found anywhere in the set
while (!admissible.contains(string1))  {
    System.out.println("Enter again (Set): ");
    string1 = input.next();
} 
input.close();
Sign up to request clarification or add additional context in comments.

5 Comments

Also, which way would be the fastest: using booleans, using sets, or using regexes?
You can answer the performance question definitively only with a good benchmark. My bet would be that !string1.equals("A") && !string1.equals("B") && ... will be the most efficient for small number of elements. At some number the set will become better. I don't think regex will be the worst variant as it's essentially the same as !string1.equals("A") && !string1.equals("B") && ... but with some overhead.
Sure. Is it recommended that I should note that the first method, the "naive" or "plain" method using only booleans is the most recommended for small amount of elements? Or is the comment good enough?
Well, is it "the most recommended"? Do you have any proof of that? My comment is just my guess.
Then, even assuming it's the most efficient way - that does not make it recommended. I personally would prefer using set with the appropriate implementation.
1

As Hemant stated in their comment, it'd be smart to use a Set to store whatever Strings you want to check against:

Set<String> words = Set.of("Hello", "World!");

while (!words.contains(string1)) {
    ...
}

Note: Set#of was introduced in Java 9, and string1 is the String that you're checking against.

Comments

1
// static set at top of the class
private static final Set<String> SET = new HashSet<>
                                (Arrays.asList("A", "B", "C", "D"));

void func() {

    String input = takeInput();
    while(!SET.contains(input)) {

        input = takeInput();
    }
}

4 Comments

Don't know why, but that uppercase set troubles me xD
It can be changed to meaningful name, since we don't know the context, we can't tell exact name of variable
@NiVeR Uppercase is fine for constants. What troubles me is a non-meaningful name SET.
@lexicore I was indeed referring to this. Uppercase for constants is perfectly fine.
1

One approach is to construct a simple regular expression to match your strings:

String input = "";
while (!Pattern.matches("FirstString|SecondString|ThirdString", input)) {
    ...
}

Regular expression pattern is composed of the words that you wish to allow separated by the vertical bar | character.

Note: Using while loop requires setting input to a non-matching String before entering the loop. You can improve upon this by changing to do / while loop:

String input;
do {
    System.out.println("Please enter a correct option");
    input = takeInput();
} while (!Pattern.matches("FirstString|SecondString|ThirdString", input));

2 Comments

Would I have to import something for the pattern function?
@lexicore It depends on the benchmark. In cases where user input is required there would be no discernible difference even with a linear array search of 100+ items, even if it is performed by trained circus mice ;-)

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.