在开关内使用枚举

发布于 2024-11-09 03:00:57 字数 373 浏览 0 评论 0原文

我们可以在开关内使用枚举吗?

public enum Color {
  RED,BLUE,YELLOW


}


 public class Use {
  Color c = Color.BLUE;

  public void test(){
      switch(c){
      case Color.BLUE:

      }
  }
}

我在这方面遇到一些错误。

The enum constant Color.BLUE reference cannot be qualified in a case label  Use.java        line 7  Java Problem

Can we use enum inside a switch?

public enum Color {
  RED,BLUE,YELLOW


}


 public class Use {
  Color c = Color.BLUE;

  public void test(){
      switch(c){
      case Color.BLUE:

      }
  }
}

I am getting some error in this.

The enum constant Color.BLUE reference cannot be qualified in a case label  Use.java        line 7  Java Problem

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

忘年祭陌 2024-11-16 03:00:57
case COLOR.BLUE:

    }

在上面的代码中,只写 BLUE


E.G,而不是 COLOR.BLUE。

import java.awt.Color;

class ColorEnum {

    enum Color{BLUE,RED,YELLOW};

    public static void main(String[] args) {
        Color c = Color.BLUE;
        switch(c) {
            case BLUE:
                System.out.println("Blue!");
                break;
            case RED:
                System.out.println("Red!");
                break;
            case YELLOW:
                System.out.println("Yellow!");
                break;
            default:
                System.out.println("Logic error!");
        }
    }
}
case COLOR.BLUE:

    }

In the above code instead of COLOR.BLUE only write BLUE


E.G.

import java.awt.Color;

class ColorEnum {

    enum Color{BLUE,RED,YELLOW};

    public static void main(String[] args) {
        Color c = Color.BLUE;
        switch(c) {
            case BLUE:
                System.out.println("Blue!");
                break;
            case RED:
                System.out.println("Red!");
                break;
            case YELLOW:
                System.out.println("Yellow!");
                break;
            default:
                System.out.println("Logic error!");
        }
    }
}
北渚 2024-11-16 03:00:57

像这样写:

public void test(){
  switch(c) {
  case BLUE:

  }
}

enum 标签用作 case 标签时不得进行限定。 JLS 14.11 的语法是这样说的

SwitchLabel:
    case ConstantExpression :
    case EnumConstantName :
    default :

EnumConstantName:
    Identifier

:需要一个简单的标识符,而不是由枚举名称限定的标识符。

(我不知道他们为什么这样设计语法。可能是为了避免语法中的一些歧义。但无论如何,事情就是这样。)

Write it like this:

public void test(){
  switch(c) {
  case BLUE:

  }
}

The enum label MUST NOT be qualified when used as a case label. The grammar at JLS 14.11 says this:

SwitchLabel:
    case ConstantExpression :
    case EnumConstantName :
    default :

EnumConstantName:
    Identifier

Note that a simple identifier is require, not an identifier qualified by the enum name.

(I don't know why they designed the syntax like that. Possibility it was to avoid some ambiguity in the grammar. But either way, that's the way it is.)

似梦非梦 2024-11-16 03:00:57

为什么要使用开关?而是让枚举本身保存颜色信息(封装它),从而完成所有脏工作。这样做的优点是,如果您更改枚举,则不必遍历所有使用它的代码,更改所有 switch 语句。例如:

import java.awt.Color;

public enum MyColor {
   RED("Red", Color.red), BLUE("Blue", Color.blue), 
   YELLOW("Yellow", Color.yellow);

   private String text;
   private Color color;
   private MyColor(String text,Color color) {
      this.text = text;
      this.color = color;
   }

   public String getText() {
      return text;
   }

   public Color getColor() {
      return color;
   }

   @Override
   public String toString() {
      return text;
   }
}

如何使用它的示例如下:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
class MyColorTest extends JPanel {
   private static final Dimension PREF_SIZE = new Dimension(400, 300);

   public MyColorTest() {
      for (final MyColor myColor : MyColor.values()) {
         add(new JButton(new AbstractAction(myColor.getText()) {
            @Override
            public void actionPerformed(ActionEvent arg0) {
               MyColorTest.this.setBackground(myColor.getColor());
            }
         }));

      }
   }

   @Override
   public Dimension getPreferredSize() {
      return PREF_SIZE;
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("MyColorTest");
      frame.getContentPane().add(new MyColorTest());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }

}

Why use a switch at all? Rather just let the enum hold the Color information itself (encapsulate it) and thereby do all the dirty work. The advantage to this, is if you change your enum, you don't have to root through all code that uses it, changing all switch statements. For instance:

import java.awt.Color;

public enum MyColor {
   RED("Red", Color.red), BLUE("Blue", Color.blue), 
   YELLOW("Yellow", Color.yellow);

   private String text;
   private Color color;
   private MyColor(String text,Color color) {
      this.text = text;
      this.color = color;
   }

   public String getText() {
      return text;
   }

   public Color getColor() {
      return color;
   }

   @Override
   public String toString() {
      return text;
   }
}

and an example of how this can be used is as follows:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
class MyColorTest extends JPanel {
   private static final Dimension PREF_SIZE = new Dimension(400, 300);

   public MyColorTest() {
      for (final MyColor myColor : MyColor.values()) {
         add(new JButton(new AbstractAction(myColor.getText()) {
            @Override
            public void actionPerformed(ActionEvent arg0) {
               MyColorTest.this.setBackground(myColor.getColor());
            }
         }));

      }
   }

   @Override
   public Dimension getPreferredSize() {
      return PREF_SIZE;
   }

   private static void createAndShowUI() {
      JFrame frame = new JFrame("MyColorTest");
      frame.getContentPane().add(new MyColorTest());
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }

}
拍不死你 2024-11-16 03:00:57

是的,您可以在 switch 语句中使用枚举,但请确保不要在 case 标签中使用 FQCN(完全限定类名)。


以下内容摘自“枚举常量引用无法限定”在 switch 语句的 case 标签中

简而言之

当 Java switch 语句使用 enum 参数时;枚举值的限定名称不应在 case 标签中使用,而只能使用非限定名称;那么 switch 语句将认为所有标签都引用用作参数的枚举类型。

为什么只有不合格的值?

如果案例标签允许合格的参考;无法限制标签中使用的枚举类型与 switch 语句的参数类型相同。

public enum Status {
    REGISTERED,
    TERMINATED
}

public class TestStatus {
    public static String getMessage(Status status) {
        String message;
        switch (status) {
            // case Status.REGISTERED: // line 1
            case REGISTERED: // line 2
                message = "Welcome";
                break;
            default:
                message = "Good bye";
                break;
        }
    return message;
}

Yes, you can use enums in switch statements, but make sure not to use FQCN (fully-Qualified Class Name) in case labels.


Following is extracted from "enum constant reference cannot be qualified in a case label of switch statement"

In Short

When a Java switch statement uses an enum parameter; qualified names of the enum values should not be used in case labels, but only the unqualified names; then switch statement will consider all the labels are referring to the enum type that is used as the parameter.

Why only unqualified values?

If qualified references were allowed for case labels; there would be no means to restrict the enum type used in the labels to be same as the parameter type of switch statement.

public enum Status {
    REGISTERED,
    TERMINATED
}

public class TestStatus {
    public static String getMessage(Status status) {
        String message;
        switch (status) {
            // case Status.REGISTERED: // line 1
            case REGISTERED: // line 2
                message = "Welcome";
                break;
            default:
                message = "Good bye";
                break;
        }
    return message;
}
定格我的天空 2024-11-16 03:00:57
enum MyEnum{
    A,B,C

    MyEnum(){
        switch(this){
            case A:
                 //....
                 break;
            case B:
                 //....
                 break;
            case C:
                 //....
                 break;
        }
    }
}
enum MyEnum{
    A,B,C

    MyEnum(){
        switch(this){
            case A:
                 //....
                 break;
            case B:
                 //....
                 break;
            case C:
                 //....
                 break;
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文