我试图手动测试我的枚举旋转方法next()但它没有返回任何东西,很可能是null。当我分配一些变量tester = Rotation.CW0然后调用方法next()时,该方法应返回CW90,但它不返回任何内容。 COul请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;
}
答案 0 :(得分:3)
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;
}
}
答案 1 :(得分:3)
怎么样:
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];
}
}
但它没有给我任何回报,
好tester.next();
代码会返回一些内容,但您不会在任何地方存储和使用它,因此可能会将代码更改为
Rotation tester = Rotation.CW0;
System.out.println(tester.next());
答案 2 :(得分:1)
将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;
}
}