尝试测试 Enum 的方法

Trying to test Enum's method

我正在尝试手动测试我的枚举 Rotation 方法 next(),但它 return 什么也没给我,很可能是 null。当我分配一些变量 tester = Rotation.CW0 然后调用方法 next() 时,该方法应该 return CW90 但其 return 什么也没有。请smb看看我在代码中做错了什么?

public class Tester {

    public static void main(String[] args)
    {
        Rotation tester = Rotation.CW0;
        tester.next();
    }
}
public enum Rotation {

    CW0, CW90, CW180, CW270;

    // Calling rot.next() will return the next enumeration element
    // representing the next 90 degree clock-wise rotation after rot.
    public Rotation next()
    {
        if(this == CW0)
            return CW90;
        else if(this == CW90)
            return CW180;
        else if(this == CW180)
            return CW270;
        else if(this == CW270)
            return CW0;

        return null;
    }

将 next() 的结果返回给测试者:

public static void main(String[] args) throws Exception {
    Rotation tester = Rotation.CW0;
    tester = tester.next();
    System.out.println(tester);
}

public enum Rotation {

    CW0, CW90, CW180, CW270;

    // Calling rot.next() will return the next enumeration element
    // representing the next 90 degree clock-wise rotation after rot.
    public Rotation next() {
        if (this == CW0) {
            return CW90;
        } else if (this == CW90) {
            return CW180;
        } else if (this == CW180) {
            return CW270;
        } else if (this == CW270) {
            return CW0;
        }

        return null;
    }
}
public class Tester {

    public static void main(String[] args) {
        Rotation tester = Rotation.CW0;
        System.out.println(tester.next());
    }
}

public enum Rotation {

    CW0, CW90, CW180, CW270;

    public Rotation next() {
        switch (this) {
        case CW0:
           return CW90;
        case CW90:
           return CW180;
        case CW180:
           return CW270;
        case CW270:
           return CW0;
        }
        return null;
    }
}

怎么样:

enum Rotation {

    CW0, CW90, CW180, CW270;

    //here we know that that all enum variables are already created
    //so we can now set them up
    static{
        CW0.next = CW90;
        CW90.next = CW180;
        CW180.next = CW270;
        CW270.next = CW0;
    }

    private Rotation next;

    public Rotation next() {
        return this.next;
    }
}

或者更神秘一些

enum Rotation {

    CW0, CW90, CW180, CW270;

    //to prevent recreating array of values in each `next()` call
    private static final Rotation[] values = values();
    private static final int LENGTH = values.length;

    public Rotation next() {
        return values[(this.ordinal() + 1) % LENGTH];
    }
}

but it's returning me nothing,

很好 tester.next(); 代码 returns 你的东西,但你没有在任何地方存储和使用它所以也许将你的代码更改为

Rotation tester = Rotation.CW0;
System.out.println(tester.next());