Sunday, June 30, 2019

java - Take string and compare to multiple enum types all at once





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.


Answer



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;
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...