Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum, integer and string together define?

I want to define string and integer together but it gives errors.

public class Card {
    Rank rank;
    Suit suit;
    public Card(Rank rank, Suit suit){
        this.rank=rank;
        this.suit=suit;
    }
    public enum Rank { Ace, 9, Queen, King } //and other suits
}

The error is a syntax error on token 9, delete this token.

like image 346
CursedChico Avatar asked Aug 15 '13 08:08

CursedChico


People also ask

Can we give string value in enum?

When working with enums in C#, it is sometimes necessary to get a string description of the value associated with the enum. This can be accomplished easily by using the DescriptionAttribute class.

Can enum have multiple values?

The Enum constructor can accept multiple values.

Can we use enum as string in Java?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.


2 Answers

In declaring enum in Java { Ace, 9, Queen, King } these are not strings and integers. These are actual objects of enum.

You can do this:

 public enum Rank { 
     Ace(13), 
     Nine(8),
     //etc
     ;

     private int rank;

     Rank(int rank) {
         this.rank = rank;
     }

     public int getRank() { 
         return rank;
     }
 }
like image 51
Tala Avatar answered Sep 24 '22 18:09

Tala


The things inside enums are identifiers, names of static final (constant) objects that'll be created. So, you can't use an int for naming an object.

enums allow you to place fields for each entry:

public static enum Suit {HEART,DIAMOND,SPADE,CLUB}

public static enum Cards {
    ACE_OF_HEART(Suit.HEART,14), QUEEN_OF_SPADE(Suit.SPADE,13) /* etc etc*/;

    private final Suit mSuit;
    private final int mRank;

    private Cards(Suit suit, int rank) {
        assert rank >= 2 && rank <= 14;
        mSuit = suit;
        mRank = rank;
    }

    public Suit getSuit() {
        return mSuit;
    }

    public int getRank() {
        return mRank;
    }
}

You really don't want to code all 52 cards this way. You can model it another way:

Suite:

public static enum Suit { SPADE, HEART, DIAMOND, CLUB};

Class with some popular ranks as named constants:

public class Card{

  public static final int ACE = 14;
  public static final int QUEEN = 13;
  public static final int KING = 12;
  public static final int JACK = 11;

  private final int mRank;
  private final Suite mSuit;

  public Card(Suite s, int r){
    this.mSuit = s;

    if(r < 2 || r > 14){
      throw new IllegalArgumentException("No such card with rank: "+r);
    }    

    this.mRank = r;
  }

  public Suit getSuit() {
        return mSuit;
    }

    public int getRank() {
        return mRank;
    }
}
like image 27
S.D. Avatar answered Sep 22 '22 18:09

S.D.