0

I have defined an enum in a class A

public class A{

     public static final String CANDY = "yelow candy";
     public static final String CAKE = "cookie";

    public enum Yummy{
         CANDY, CAKE; 
    }

}

In another package,

public class C {

   Yummy[] yummies = A.Yummy.values();

   for (Yummy yum : yummies){
          String yumString = yum.toString();
          System.out.println("yum =" + yumString);
   }

}

I get CANDY and CAKE as a result, not "yelow candy" and "cookie". What does I need to change to get the "yelow candy" and "cookie ?

Makoto
  • 765
  • 2
  • 17
  • 45

4 Answers4

6

You've defined an enum "A.Yummy" and also two strings, "A.Candy" and "A.CAKE".

They aren't linked at all.

You will want to delete the strings and add something like https://stackoverflow.com/a/13291109/1041364

public enum Yummy {
     CANDY("yelow candy"),
     CAKE("cookie");

     private String description;

     private Yummy(String description) {
         this.description= description;
     } 

     public String toString() {
         return this.description;
     }
}
Community
  • 1
  • 1
Andrew Stubbs
  • 4,322
  • 3
  • 29
  • 48
2

Try the following:

public enum Yummy{
     CANDY ("yellow candy"), CAKE ("cookie");

     private String name;

     private Yummy(String name) {
         this.name = name;
     } 

     public String toString() {
         return this.name;
     }
}
ovunccetin
  • 8,443
  • 5
  • 42
  • 53
1

Additional values for enums should be hold in properties. You have to provide constructor to set up those properties.

  public enum Yummy {
    CANDY("yelow candy"), CAKE("cookie");
    private String value;

    private Yummy(String value) {
      this.value = value;
    }
  };

And then in code you can use CANDY.value or override toString() method.

Kasper Ziemianek
  • 1,329
  • 8
  • 15
1

Try this:

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        for (Yummy yum : Yummy.values()) {
            System.out.printf("%s, %s\n", yum, yum.getValue());
        }
    }
}
enum Yummy {
    CANDY("yelow candy"),
    CAKE("cookie");

    private String value;

    private Yummy(String value) {
        this.value = value;
    }

    public String getValue() {
        return this.value;
    }
}