Java如何将Scanner输入与ENUM进行比较

3

我正在尝试通过将字符串(来自Scanner)的结果与潜在值的枚举进行比较来获得输入验证。

该枚举包含世界上所有国家的名称,用户被要求输入一个国家名称--只有当输入值存在于枚举中时才允许输入--有没有一种方法可以做到这一点?

谢谢!

5个回答

2

最高效的方法是通过名称获取枚举并捕获异常,使用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
}

1
你可以为枚举类添加一个方法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;
        }
    }
}

现在,当用户输入“Neverland”时,显然getByName('Neverland')会返回null,您可以进行测试。您可以在列表中包括一个捕获所有值的值,并返回该值,例如TERRAINCOGNITA,而不是null

1

1
你测试过这个吗? - RealSkeptic
2
valueOf会抛出异常,而不是返回null。 - JustinKSU

0

以下应该可以工作

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

如果我在 switch case 中使用 Enum.valueOf,它会处理异常吗? Switch (enumVariable) case IND: 代码 default: “这不是一个有效的输入,请重新输入”; - user5568948
在Java中,异常只能通过try/catch或throws子句处理,switch无法防止异常的发生。在将参数传递给具有枚举案例参数的switch之前,必须将输入转换为枚举常量,在此时您将不得不处理异常。 - 11thdimension

0
public enum RegisterType {GUIDE, VISITOR, TICKET, RECEPTIONIEST;}

RegisterType type = RegisterType.valueOf(input.next());

4
请让我知道需要翻译的完整内容。 - Ilya Sazonov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接