我在这里试图获取并在类对象中设置枚举,但不知道如何做到这一点.这就是我到目前为止所拥有的.我已经抬起头来,我可以看到一些看起来太复杂的例子让我无法理解.有什么帮助吗?
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());
}
Run Code Online (Sandbox Code Playgroud)
}
您可以使用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
}
}
Run Code Online (Sandbox Code Playgroud)