使用int输入获取枚举常量作为输出

时间:2018-12-04 15:16:24

标签: java enums

我需要编写一个输出星期几的代码,该代码在枚举中是一个常量。输入是一个整数,该方法将int转换为常数。例如,当输入为0时,我应该将周日作为输出,如果数字大于6,则必须使用%来表示从8到星期二的值。如何从枚举中输出特定常量?

最后一行是不正确的,这是一个我不知道如何实现的想法

import java.util.scanner;

public class CalendarUtil{

    public static void main(String[] args){

        enum Months{
            JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER;
        }
        enum Weekdays{
            SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
        }

        Scanner s= new Scanner();
        int day = s.nextInt();

        System.out.println(getNthWeekday(int day));

    }
    public static String getNthWeekday(int day){

        if (day≥0)%6 {
            return enum
        }

    }

}

3 个答案:

答案 0 :(得分:2)

您可以尝试

import java.util.Scanner;

class CalendarUtil{

    enum Months{
        JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER;
    }

    enum Weekdays{
        SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
    }

    public static void main(String[] args){    
        Scanner s= new Scanner(System.in);
        int day = s.nextInt();
        System.out.println(getNthWeekday(day));
    }

    public static String getNthWeekday(int day){
     return Weekdays.values()[day%7].name();
    }
}

答案 1 :(得分:0)

您也可以这样:

private static String getNthWeekday(int day) {

    Weekdays[] days = Weekdays.values();

    if (day >= days.length) {
        return days[day - days.length].name();
    } else {
        return days[day].name();
    }

}

答案 2 :(得分:0)

Java的枚举为枚举的每个成员提供ordinal()方法,而values()则允许您获取所有成员。这里是建议的解决方案:

public static Weekdays getNthWeekday(int day) {
    for (Weekdays d : Weekdays.values()) {
        if (d.ordinal() == day) {
            return d;
        }
    }
    throw new IllegalArgumentException("Unknown day: " + day);
}