Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take string and compare to multiple enum types all at once [duplicate]

Tags:

java

enums

I really need help here.

If I have my separate class, lets call it FileType.java, and it looks like this:

 public enum FileType
 {
     JPG,GIF,PNG,BMP,OTHER
 }

and then I grab a string from the user, call it inputString, how can I compare "inputString" to every single enum value, with the most minimal amount of code?

EDIT: Here is what I have tried:

    System.out.print("Please enter your photo's file type. It must be: JPG, GIF, PNG, BMP, or OTHER");
    typeInput = kb.nextLine();

    boolean inputMatches = false;

    while(inputMatches == false)
    {
        System.out.print("Invalid input. Please enter your photo's file type. It must be: JPG, GIF, PNG, BMP, or OTHER");

        if(typeInput.equalsIgnoreCase(FileType.values()))
        {
            inputMatches = true;
        }
    }

Ps. I am well aware that I can just set individual variables to equal the same strings as the enum values. I;m also aware that I could use .valueOf() for every single value.

like image 388
Chisx Avatar asked Feb 17 '14 05:02

Chisx


People also ask

Can you use == for enums?

Because there is only one instance of each enum constant, it is permissible to use the == operator in place of the equals method when comparing two object references if it is known that at least one of them refers to an enum constant.

How do you compare strings to enums?

To compare a string with an enum, extend from the str class when declaring your enumeration class, e.g. class Color(str, Enum): . You will then be able to compare a string to an enum member using the equality operator == .

Are enums faster than strings?

Comparisons of enums usually are faster than comparisons of strings.


1 Answers

You can convert input to enum instead

System.out.print("Please enter your photo's file type. It must be: JPG, GIF, PNG, BMP, or OTHER");
boolean typeInput = kb.nextLine();

inputMatches = true;
try{
    FileType fileType = FileType.valueOf(inputString.toUpperCase().trim());
}catch (IllegalArgumentException e) {
    inputMatches = false;
}     
like image 162
Ajinkya Avatar answered Oct 26 '22 13:10

Ajinkya