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.

Ajinkya
  • 22,324
  • 33
  • 110
  • 161
Chisx
  • 1,976
  • 4
  • 25
  • 53

1 Answers1

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;
}     
Ajinkya
  • 22,324
  • 33
  • 110
  • 161
  • @Chisx: Just to remove spaces – Ajinkya Feb 17 '14 at 05:50
  • 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 – Chisx Feb 17 '14 at 05:51
  • I've never seen "try" and "catch", but this is a great answer regardless @Karna – Chisx Feb 17 '14 at 05:57
  • Hey what is the 'e' after the IllegalArgumentException?? @Karna – Chisx Feb 17 '14 at 06:20
  • 1
    @Chisx [Lesson: Exceptions](http://docs.oracle.com/javase/tutorial/essential/exceptions/) – Radiodef Feb 17 '14 at 06:38
  • @Chisx: Please read some tutorials before you jump and start coding. – Ajinkya Feb 17 '14 at 07:33
  • Thank you Karna, I agree completely, but we have not covered exceptions in my college's sophomore level "Intro II" course. That is why I was not even thinking about using an exception. @Karna – Chisx Feb 17 '14 at 17:18