Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int values with string values in enum

Tags:

java

enums

How can I make cards Enum in Java similar to:

public enum Card {2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace};

I tried {"2", "3"...}. It's not working either

like image 431
Vildan Avatar asked Dec 27 '22 13:12

Vildan


1 Answers

The JLS (Java Language Specification) tells us two important facts:

  1. Java enum fields must be valid identifiers.

    EnumConstants:
        EnumConstant
        EnumConstants , EnumConstant
    
    EnumConstant:
        Annotations_opt Identifier Arguments_opt ClassBody_opt
    
    Arguments:
        ( ArgumentList_opt )
    
    EnumBodyDeclarations:
        ; ClassBodyDeclarations_opt
    
  2. The first character of an identifier must be a "Java letter."

    The "Java letters" include uppercase and lowercase ASCII Latin letters A-Z (\u0041-\u005a), and a-z (\u0061-\u007a), and, for historical reasons, the ASCII underscore (_, or \u005f) and dollar sign ($, or \u0024). The $ character should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.

You must work within these restrictions.

public enum Card {
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    Ten,
    Jack,
    Queen, 
    King,
    Ace;
}
like image 160
Matt Ball Avatar answered Jan 05 '23 04:01

Matt Ball