简体   繁体   中英

Converting String to Enum give Error in java?

All The Examples of String to Enum Convertion taking only one String But In my Example String like this...

String allDays="MONDAY,SUNDAY,FRIDAY";

and My Enum Class like this..

public enum WeekdayType {

    MONDAY(Calendar.MONDAY), TUESDAY(Calendar.TUESDAY), WEDNESDAY(
            Calendar.WEDNESDAY), THURSDAY(Calendar.THURSDAY), FRIDAY(
            Calendar.FRIDAY), SATURDAY(Calendar.SATURDAY), SUNDAY(
            Calendar.SUNDAY);

    private int day;

    private WeekdayType(int day) {
        this.day = day;
    }

    public int getDay() {
        return day;
    }
}

So in that Time WeedayType.valueOf(allDay) is giving error..... Any suggestions for this..

Try like this:

String allDays = "MONDAY,SUNDAY,FRIDAY";
        for (String day : allDays.split(",")) {
            System.out.println(WeekdayType.valueOf(day));
        }

You will be getting the below error

java.lang.IllegalArgumentException: No enum const class com.java.core.Test$WeekdayType.MONDAY,SUNDAY,FRIDAY

The reason is you are passing the following String to your WeedayType enum, which is an illegal argument as the exception says.

String allDays = "MONDAY,SUNDAY,FRIDAY"; 
WeedayType.valueOf(allDay); 

The valid values you can pass to valueOf method are "MONDAY", "TUESDAY" etc.(ie your enum names). Other values gives you java.lang.IllegalArgumentException which is the correct behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM