简体   繁体   English

将字符串转换为枚举在Java中给出错误?

[英]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 to Enum转换的示例仅采用一个字符串,但是在我的示例字符串中,像这样...

String allDays="MONDAY,SUNDAY,FRIDAY";

and My Enum Class like this.. 和我的Enum Class这样。

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.. 所以在那段时间WeedayType.valueOf(allDay)给出了错误.....对此的任何建议。

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传递给您的WeedayType枚举,如异常所示,这是一个非法参数。

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). 您可以传递给valueOf方法的有效值为“ MONDAY”,“ TUESDAY”等(即您的枚举名称)。 Other values gives you java.lang.IllegalArgumentException which is the correct behaviour. 其他值给出java.lang.IllegalArgumentException,这是正确的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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