Java - Enumerated types in IF statements

87 Views Asked by At

So with my basic code I was curious if it is possible to have an if statement like below:

if (ScannerInput.equalsIgnoreCase(AllEnums)){
    System.out.println("Sample");
}

If you understand I wish to have just the name of an Enum for example for it to be true to all values. If this is possible, how do I go about it?

Here is an example of what I mean:

import java.util.Scanner;

public class EnumTest {
    enum Weather {Sunny, Rainy, Snowy, Overcast, Stormy};

    public static void main (String[] args) {
        Scanner scan = new scanner(System.in);
        String userinput = nextLine;

        if (userinput.equalsIgnoreCase(Weather.all) // I wish for this to occur if any of the Weather enums are entered.
            System.out.println ("Working!");
        }
    }
}
3

There are 3 best solutions below

0
Krusty the Clown On

Well, I guess I'm a little confused, maybe try something like this?

for(Test t:Test.values()){
    if(ScannerInput.equals(t)){
        System.out.println("Sample");
    }
}
0
Joop Eggen On
enum Color { RED, GREEN, BLUE }

String input = ...

try {
    Color c = Color.valueOf(input.trim().replace(' ', '_').toUpperCase());
    ...
} catch (IllegalArgumentException e) {
    ...
}

In your case you would need something like StringUtils.capitalize from apache commons. Or use the the convention of having capitals only enum constants. (In the case of java.awt.Color they could not decide and had all small letter versions too.)

0
Scorpio On

You could add a method to your enum-class that checks whether or not a value is within that enum:

public boolean contains(String s) {
    for (YourEnum yourEnum : values()) {
        return yourEnum.toString().equalsIgnoreCase(s);
    }
    return false;
}

This would require a near-perfect match though, which is unreliable considering someone enters the value on a console (or similar).