簡體   English   中英

Java 比較 Scanner Input 和 ENUM

[英]Java comparing Scanner Input with ENUM

我試圖通過將字符串(來自掃描儀)的結果與潛在值的枚舉進行比較來獲得輸入驗證。

Enum 包含世界上所有國家/地區的名稱,要求用戶輸入國家/地區名稱 - 只有在 Enum 中存在輸入值時才允許輸入 - 有沒有辦法做到這一點?

謝謝!

最有效的方法是嘗試使用Enum.valueOf(String)方法按名稱獲取Enum並捕獲異常:

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
}

如果字符串值作為枚舉類型存在,則使用Enum.valueOf("string") != null

在此處查找更多參考-http: //www.tutorialspoint.com/java/lang/enum_valueof.htm

以下應該工作

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

您可以為Enum配備getByName(String name) ,如果該Enum不包含給定名稱的相應值,則該方法返回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 ,您可以對其進行測試。 除了null您還可以在列表中包含一個TERRAINCOGNITA值,然后將其返回,例如TERRAINCOGNITA

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM