-5

我在这里试图在类对象中获取和设置一个枚举,但不知道该怎么做。这就是我到目前为止所拥有的。我已经查阅了所有可能的例子,有些例子似乎太复杂了,我无法理解。请问有什么帮助吗?

public class EnumExample {

public static class Task {

    private String _task;

    public enum Priority {

        ZERO (0), MAYBE (1), LOW (2), MEDIUM (3), HIGH (4), EXTREME (5);

        private int _priority;

        Priority() {
            _priority = 0;
            // Does this set set the default priority level to 0??
        }

        Priority(int priority) {
            _priority = priority;
            // This is where I can set the priority level of this task??
        }

        public int getPriority() {
            return _priority;
        }

        public void setPriority(int priority) {
            _priority = priority;
        }
    }
}



public static void main(String[] args) {

    Task task = new Task();
    task._task = "Study for test";
    System.out.println(task._task);
    System.out.println(task.getPriority());

    // How do I set the priority level for task "study for test"??
    // task.Priority = task.Priority.EXTREME;

    // How do I retrieve the value of priority??
    // System.out.println(task._task.getPriority());

}

}

4

2 回答 2

8

您可以使用ordinal()枚举的方法来获取它的位置。然后,您可以使用它来获取值优先级。

public class Task {

    private Priority priority = Priority.ZERO; // Default priority
    private String name = "";

    public enum Priority {
        ZERO, MAYBE, LOW, MEDIUM, HIGH, EXTREME;
    }

    public Task(String name) {
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
       return name;
    }

    public void setPriority(Priority p) {
        this.priority = p;
    }

    public Priority getPriority() {
        return priority
    }

    public static void main(String[] args) {
        Task t = new Task("Washing up");
        t.setPriority(Priority.HIGH);
        System.out.println(t.getName()); // Washing up
        System.out.println(t.getPriority().toString()); // This gets the string of HIGH
        System.out.println(t.getPriority().ordinal()); // this gives 4
    }
}
于 2013-02-17T21:24:54.507 回答
0

你已经在你的类中定义了一个名为 Priority 的枚举类型,但是为了让你的任务有一个优先级,你必须在你的类中有一个 Priority 类型的成员变量:

public static class Task {

    private String task;

    private Priority priority;

然后,您只需通过设置成员来使用您的任务,例如使用 setter 方法:

    public Priority getPriority() {
        return priority;
    }

    public Priority setPriority(Priority priority) {
        this.priority = priority;
    }

然后在你的主要方法中:

 task.setPriority(Priority.LOW);

关于枚举中的 getter/setter,由于 Priority 类型的语义是表示某个固定优先级,因此您不应该有 setter。您可能还可以摆脱变量本身(因此也摆脱了 getter),因为枚举本身很好地代表了任务的优先级(并且枚举默认情况下已经有一个序数)。

因此枚举声明可以很简单:

public enum Priority {
        ZERO, MAYBE, LOW, MEDIUM, HIGH, EXTREME;
}

注意:按照标准 Java 代码样式,您不应该将下划线作为成员的开头。改用驼峰式。

于 2013-02-17T21:22:22.520 回答