我正在尝试通过将字符串(来自Scanner)的结果与潜在值的枚举进行比较来获得输入验证。
该枚举包含世界上所有国家的名称,用户被要求输入一个国家名称--只有当输入值存在于枚举中时才允许输入--有没有一种方法可以做到这一点?
谢谢!
我正在尝试通过将字符串(来自Scanner)的结果与潜在值的枚举进行比较来获得输入验证。
该枚举包含世界上所有国家的名称,用户被要求输入一个国家名称--只有当输入值存在于枚举中时才允许输入--有没有一种方法可以做到这一点?
谢谢!
最高效的方法是通过名称获取枚举并捕获异常,使用Enum.valueOf(String)方法:
try {
CountryEnum country = CountryEnum.valueOf( "user-input" );
} catch ( IllegalArgumentException e ) {
System.err.println( "No such country" );
}
另一种不使用捕获异常的方法是将用户输入与每个枚举值进行比较:
String userInput = ...;
boolean countryExists = false;
for( CountryEnum country : CountryEnum.values() ) {
if( userInput.equalsIgnoreCase( country.name() ) ) {
countryExists = true;
break;
}
}
if( !countryExists ) {
System.err.println( "No such country" );
// exit program here or throw some exception
}
getByName(String name)
,如果该枚举类没有对应名称的值,则返回null
:public enum Country {
AFGHANISTAN,
ALBANIA,
ALGERIA,
...
public static Country getByName(String name) {
try {
return valueOf(name.toUpperCase());
} catch (IllegalArgumentException e) {
return null;
}
}
}
getByName('Neverland')
会返回null
,您可以进行测试。您可以在列表中包括一个捕获所有值的值,并返回该值,例如TERRAINCOGNITA
,而不是null
。Enum.valueOf("string") != null
。以下应该可以工作
public class EnumTest {
enum Country{IND, AUS, USA;
static boolean exists(String key) {
Country[] countryArr = values();
boolean found = false;
for(Country country : countryArr) {
if(country.toString().equals(key)) {
found = true;
break;
}
}
return found;
}
};
public static void main(String[] args) {
System.out.println("Started");
Scanner scan = new Scanner(System.in);
System.out.println(Country.exists(scan.nextLine()));
scan.close();
}
}
当然,您可以通过使用Set来存储值来实现更有效的搜索。
不能使用Enum.valueOf,因为当传递的值与任何枚举常量不匹配时,它会抛出以下异常。
java.lang.IllegalArgumentException: No enum constant
public enum RegisterType {GUIDE, VISITOR, TICKET, RECEPTIONIEST;}
RegisterType type = RegisterType.valueOf(input.next());