Java enumeration variables, integer and string together define?

I want to define a string and an 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 in token 9, delete this token.

+7
java enums integer
source share
6 answers

In the listing declaration in Java { Ace, 9, Queen, King } these are not strings or integers. These are actual enumeration objects.

You can do it:

  public enum Rank { Ace(13), Nine(8), //etc ; private int rank; Rank(int rank) { this.rank = rank; } public int getRank() { return rank; } } 
+8
source share

Things inside enum are identifiers, the names of the static finite (persistent) objects that will be created. Thus, you cannot use int to name an object.

enum allows you to place fields for each record:

 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 do not want to encode all 52 cards in this way. You can model it differently:

Suite:

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

A 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; } } 
+6
source share

You cannot start an enumeration field with a number. Try using NINE .

+3
source share

The Java naming conventions say that you cannot run variables, class names ect ... with numbers.

+2
source share

try

 public enum Rank { Ace, Jack, Queen, King }//and other suits 

instead of your listing

the problem is that if you could put the number as the value of the enumeration, the compiler will not know when someone writes "9", he meant the number or the enumeration. therefore, java, like almost every language, will not allow such a value enum

+1
source share

U cannot use integers inside an enum like this. Please proceed to the following: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

+1
source share

All Articles