如何在java中返回枚举值

Mat*_*hew 8 java enums return

我该如何返回这样的枚举?

在我用int返回之前,如果没有,则返回0,如果是,则返回1,如果是其他则返回2.但这不是一个好方法.那应该怎么做呢.我的代码:

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;
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

Kon*_*kov 8

我不是什么"//扫描仪等" 但是,返回类型的方法应该是decizion:

public static decizion yourDecizion() { ... }
Run Code Online (Sandbox Code Playgroud)

此外,还可以在添加Y,N等值枚举常量:

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();
     }
}
Run Code Online (Sandbox Code Playgroud)

然后,在该方法中,您可以这样做:

public static decizion yourDecizion() {
    ...
   String key = ...
   return decizion.getValue(key);
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我认为你应该做这样的事情,一个枚举类。然后您可以添加任意数量的类型,并且 yourDecizion() 方法将根据给定的参数返回枚举类型。

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;
    }
}
Run Code Online (Sandbox Code Playgroud)