10

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.

3
  • Show us, what you have tried. Commented Feb 17, 2014 at 5:37
  • alright here's what I've tried, but it's flawed at the moment. Commented Feb 17, 2014 at 5:39
  • why don't you use FileType.valueOf(userInput)? If it throws IllegalArgumentException the input is invalid otherwise it gives you the enum value. Commented Feb 17, 2014 at 5:47

1 Answer 1

6

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;
}     
Sign up to request clarification or add additional context in comments.

7 Comments

@Chisx: Just to remove spaces
I'm sorry but this is confusing me. Is this the conditional? Like to put in the loop? I would use this, but this is advanced for what we're doing. We have not learned exceptions yet
I've never seen "try" and "catch", but this is a great answer regardless @Karna
Hey what is the 'e' after the IllegalArgumentException?? @Karna
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.