Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum declaration in java

Tags:

java

android

I have declared enum function as follows

public static enum SHAPE


{
    static
    {
      LINE = new SHAPE("LINE", 3);
      CIRCLE = new SHAPE("CIRCLE", 4);
      TEXT = new SHAPE("TEXT", 5);
      SHAPE[] arrayOfSHAPE = new SHAPE[6];
      arrayOfSHAPE[0] = DRAW;
      arrayOfSHAPE[1] = SQUARE;
      arrayOfSHAPE[2] = TRIANGLE;
      arrayOfSHAPE[3] = LINE;
      arrayOfSHAPE[4] = CIRCLE;
      arrayOfSHAPE[5] = TEXT;
    }
  }

but I am getting

Syntax error, insert "}" to complete Block at line4 and getting Syntax error, insert "EnumBody" to complete EnumDeclaration at line1.

so please assist me in the declaration of this enum. Thanks in advance.

like image 623
indraja machani Avatar asked Feb 01 '26 04:02

indraja machani


1 Answers

There are multiple problems with your enum declaration:

  1. The static in the enum declaraction doesn't make any sense and causes a compile error.
  2. You need to define the values of the enum at the begining of the class (see below).
  3. The array declaration should be outside of the static block

This should work, I also cleared up the code a little:

public enum Shape {
    LINE("LINE", 3),
    CIRCLE("CIRCLE", 4),
    TEXT("TEXT", 5),
    // DRAW, SQUaRE, TRIANGLE, ...
    ;

    public static final Shape[] SHAPES= new Shape[6];

    static
    {
      SHAPES[0] = DRAW;
      SHAPES[1] = SQUARE;
      SHAPES[2] = TRIANGLE;
      SHAPES[3] = LINE;
      SHAPES[4] = CIRCLE;
      SHAPES[5] = TEXT;
    }

    // Constructor etc.
}

I think you don't need the SHAPES-array because you can access all values of the enum by calling: Shape.values()

like image 133
ssindelar Avatar answered Feb 03 '26 16:02

ssindelar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!