How to return enum value in java
如何返回这样的枚举?
在我用0表示不之前,1表示是,2表示其他。但这不是个好办法。那么应该怎么做呢?我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class SomeClass{ public enum decizion{ YES, NO, OTHER } public static enum yourDecizion(){ //scanner etc if(x.equals('Y')){ return YES; } else if (x.equals('N')){ return NO; } else{ return OTHER; } } } |
我不知道"//scanner等"的作用,但是方法返回类型应该是
1 | public static decizion yourDecizion() { ... } |
此外,可以将
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public enum decizion{ YES("Y"), NO("N"), OTHER; String key; decizion(String key) { this.key = key; } //default constructor, used only for the OTHER case, //because OTHER doesn't need a key to be associated with. decizion() { } decizion getValue(String x) { if ("Y".equals(x)) { return YES; } else if ("N".equals(x)) { return NO; } else if (x == null) { return OTHER; } else throw new IllegalArgumentException(); } } |
然后,在方法中,您只需执行以下操作:
1 2 3 4 5 |
我认为您应该做类似的事情,一个枚举类。然后,您可以添加任意多个您想要的类型,并且方法yourdization()将根据给定的参数返回枚举类型。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public enum SomeClass { YES(0), NO(1), OTHER(2); private int code; private SomeClass(int code) { this.code = code; } public int getCode() { return code; } public static SomeClass yourDecizion(int x) { SomeClass ret = null; for (SomeClass type : SomeClass.values()) { if (type.getCode() == x) ret = type; } return ret; } } |
将代码更改为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class SomeClass{ public enum decizion { YES, NO, OTHER } public static decizion yourDecizion(){ //scanner etc if(x.equals('Y')){ return decizion.YES; } else if (x.equals('N')){ return decizion.NO; } else{ return decizion.OTHER; } } } |
注意:方法返回类型必须是