如何比较的枚举法枚举所有可能的值的枚举的价值和避免遗漏return语句?

问题描述 投票:0回答:3

我只是学习Java中枚举。当我运行下面的代码,我得到一个错误,我也在下面重现。基本上,我的问题是:当我在一个枚举定义的方法,并在这方法我要检查的枚举,这样我可以以此为基础进行有价值的东西的价值,我该如何进行这样的检查?下面我有三个可能的值枚举,而在方法getNext,我有三个if语句与三个可能的值进行比较此枚举值。但我仍然得到一个错误,指出没有不归路。

package enumerations;

enum TrafficLightColor2 {
    RED(12), GREEN(10), YELLOW(2);

    private int waitTime;

    TrafficLightColor2(int waitTime) {
        this.waitTime = waitTime;
    }

    int getWaitTime() {
        return waitTime;
    }

    TrafficLightColor2 getNext() {
        if (this.equals(TrafficLightColor2.GREEN)) {
            return TrafficLightColor2.YELLOW;
        }
        if (this.equals(TrafficLightColor2.YELLOW)) {
            return TrafficLightColor2.RED;
        }
        if (this.equals(TrafficLightColor2.RED)) {
            return TrafficLightColor2.GREEN;
        }
    }
}

// A computerized traffic light.
class TrafficLightSimulator2 implements Runnable {
    private Thread thrd; // holds the thread that runs the simulation
    private TrafficLightColor2 tlc; // holds the traffic light color
    boolean stop = false; // set to true to stop the simulation
    boolean changed = false; // true when the light has changed

    TrafficLightSimulator2(TrafficLightColor2 init) {
        tlc = init;
        thrd = new Thread(this);
        thrd.start();
    }

    TrafficLightSimulator2() {
        tlc = TrafficLightColor2.RED;
        thrd = new Thread(this);
        thrd.start();
    }

    // Start up the light.
    public void run() {
        while (!stop) {
            try {
                Thread.sleep(tlc.getWaitTime());
            } catch (InterruptedException exc) {
                System.out.println(exc);
            }
            changeColor();
        }
    }

    // Change color.
    synchronized void changeColor() {
        tlc = tlc.getNext();
        changed = true;
        notify(); // signal that the light has changed
    }

    // Wait until a light change occurs.
    synchronized void waitForChange() {
        try {
            while (!changed)
                wait(); // wait for light to change
            changed = false;
        } catch (InterruptedException exc) {
            System.out.println(exc);
        }
    }

    // Return current color.
    synchronized TrafficLightColor2 getColor() {
        return tlc;
    }

    // Stop the traffic light.
    synchronized void cancel() {
        stop = true;
    }
}


class TrafficLightDemo2 {
    public static void main(String args[]) {
        TrafficLightSimulator tl =
                new TrafficLightSimulator(TrafficLightColor.GREEN);
        for (int i = 0; i < 9; i++) {
            System.out.println(tl.getColor());
            tl.waitForChange();
        }

        tl.cancel();
    }
}

我得到的错误

$ javac enumerations/TrafficLightDemo2.java
enumerations/TrafficLightDemo2.java:26: error: missing return statement
    }
    ^
1 error
java enums
3个回答
3
投票
TrafficLightColor2 getNext() {
    if (this.equals(TrafficLightColor2.GREEN)) {
        return TrafficLightColor2.YELLOW;
    }
    if (this.equals(TrafficLightColor2.YELLOW)) {
        return TrafficLightColor2.RED;
    }
    if (this.equals(TrafficLightColor2.RED)) {
        return TrafficLightColor2.GREEN;
    }
}

如果所有3个if都是假的这个方法不返回值。

在添加回报,或更好抛出一个错误,例如

throw new IllegalArgumentException("Unsupported enum")


1
投票

枚举类中使用实例字段的好处是,你可以实现细节很容易与您的常量独立于您的API联系起来。换句话说,你可以很容易与您的枚举常量数据会承认一个优雅的解决方案,你是不是永远的,例如,您需要添加一个新的枚举常量的情况下嫁给了关联。

所以,你可以大大简化您的实现,同时满足同一合同如下:

enum TrafficLightColor2 {
    RED(2, 12), 
    GREEN(0, 10), 
    YELLOW(1, 2);


    private int order;   // implementation detail; non-exported
    private int waitTime;

    TrafficLightColor2(int ord, int waitTime) {
        this.order = ord;
        this.waitTime = waitTime;
    }

    int getWaitTime() {
        return waitTime;
    }

    TrafficLightColor2 getNext() {
        final int nextColor = (this.order + 1) % 3;  // magic numbers introduce fragility
        return Arrays.stream(TrafficLight2.values())
                .filter(e -> e.order == nextColor)
                .findAny()
                .get();
    }
}

这个版本有一定的优势,你原来的实现:它是更容易,因为维护,如果添加了enum常量,编译器会强迫你添加一个订单价值。在原来的,如果你忘了加上一个常数后修改的if-else块,你的程序将继续工作,但它不会提供正确的行为。而由于order的实现是隐藏的,你可以自由地将其删除或随时将其更改为其他执行不影响您的API的正确性。


0
投票

你有没有考虑包括与申报值一起下一个状态?

public enum TrafficLightColor2 {
    RED(12, "GREEN"), GREEN(10, "YELLOW"), YELLOW(2, "RED");

    int waitTime;
    String nextState;
    Configurations(int waitTime, String nextState) {
        this.waitTime = waitTime;
        this.nextState = nextState;
    }
    public int getWaitTime() {
        return waitTime;
    }
    public String getNextState() {
        return nextState;
    }
}

有了这个,你可以得到下一个状态

TrafficLightColor2 trafficLightColor = TrafficLightColor2.GREEN;
System.out.println(TrafficLightColor2.valueOf(trafficLightColor.getNextState()));
© www.soinside.com 2019 - 2024. All rights reserved.