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.
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.
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 == .
Comparisons of enums usually are faster than comparisons of strings.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With