gpt4 book ai didi

java - java中的枚举声明

转载 作者:太空宇宙 更新时间:2023-11-03 11:44:09 27 4
gpt4 key购买 nike

我已经声明了枚举函数如下

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;
}
}

但是我得到了

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

所以请协助我声明这个枚举。提前致谢。

最佳答案

您的枚举声明存在多个问题:

  1. 枚举声明中的静态没有任何意义,会导致编译错误。
  2. 您需要在类(class)开始时定义枚举的值(见下文)。
  3. 数组声明应该在静态 block 之外

这应该可以,我也稍微清理了一下代码:

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.
}

我认为您不需要 SHAPES 数组,因为您可以通过调用访问枚举的所有值:Shape.values()

关于java - java中的枚举声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17802895/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com