简体   繁体   English

java:枚举声明错误说错误的构造函数

[英]java : Error in Enum Declaration Saying Misplaced Constructors

I may get result of any of the type , so i am defining enum this way 我可能得到任何类型的结果,所以我这样定义枚举

public enum Result 
     {
        1, 2,3, 4,5, 6,7, 8
     }


String resultvalue = calculateResult();

    switch (Result .valueOf(resultvalue ))
          {

          }

But i am geting error at the Enum Declaration itself saying Mispalced Constructors . 但我在Enum宣言本身就说错误的建设者。

Could anybody please help me 请有人帮帮我

Those aren't valid identifiers for enum values, basically. 它们基本上不是枚举值的有效标识符。 You'll need to prefix them with a letter or _. 你需要在它们前面添加一个字母或_。 You'll also need to make the identifiers unique - currently you've got 0010 four times... 您还需要做出独特的标识符-目前你已经有了0010的四倍...

Once you've sorted that out, the rest should probably be okay - but if you have any more problems, please post a short but complete program, rather than snippets. 一旦你对它进行了整理,剩下的应该没问题 - 但是如果你有任何问题,请发一个简短但完整的程序,而不是片段。

0001 is not a valid Java identifier. 0001不是有效的Java标识符。 A Java Identifier must not start with a digit. Java标识符不能以数字开头。

Although I don't understand what you want to achieve and why you have duplicates. 虽然我不明白你想要实现什么以及为什么你有重复。 Something like that (maybe using an int instead of String) should work. 类似的东西(可能使用int而不是String)应该可以工作。

public enum Result {
    One( "0001"),
    Two( "0010")
    ...

    private String val;

    private Result(String val) {
        this.val = val;
    }
}

I an not sure why calcuate result would return a String. 我不确定为什么计算结果会返回一个字符串。 I would return a int here but... 我会在这里返回一个int但是......

String resultvalue = calculateResult();
switch (Integer.parseInt(resultvalue)) {
   case 0b0001:

   case 0b0010:

   case 0b0110:

   case 0b1010:

   case 0b1100:

}

What is it that you are trying to achieve? 你想要达到的目标是什么? If you need to: 如果你需要:

  1. parse an integer from a string, then 然后解析字符串中的整数
  2. check that it's from a certain set of values, and finally 检查它是否来自某组值,最后
  3. switch on its value, 切换它的价值,

then you don't need an enum. 那你就不需要枚举了。 Just do it with Integer.parseInt() , Set.contains() , and switch . 只需使用Integer.parseInt()Set.contains()switch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM