質問

I'm making a blackjack program in Java, and I was starting to write the class declaration for an object Card. Will this be sufficient, or are there some methods I should have that I'm glossing over?

public class Card {
    public int suit; //Value 1-4 to represent suit
    public int value; //Value 1-13 to represent value (i.e. 2, J)
    public Card(int suit, int value) {
        //Not yet implemented
    } 
}

Also, is there a good way to have an something like C++'s enum data structure in Java, because that would be nice for card names and suits?

役に立ちましたか?

解決

public enum Suite {
    HEART, DIAMOND, CLUB, SPADE
}
public enum Value {
    TWO, THREE, ... , JACK, QUEEN, KING, ACE 
}

and the rest you can figure out.

他のヒント

Yeah, your start looks good. Switch the ranks and suits to enums - that would be a good idea. As far as methods, create them as you go and discover you need them. Depending on the game you're writing, you may need a completely different set of methods.

Java has a very powerful enum. Check out the example below.

public enum Rank {
  ACE(1, "Ace"),
  TWO(2, "Two"),
  ... etc
  KING(13, "King");

  private int value;
  private String display;

  private Rank (int value, String display) {
    this.value = value;
    this.display = display;
  }

  public int getValue() {
    return this.value;
  }

  public int getDisplay() {
    return this.display;
  }
}

I would (have) used an enum with the suit and value as properties. Suit and value can also be enums.

Java as of 1.5 fully supports enums. Coincidentally, the example provided in the link uses a card class as an example much as you are trying to do.

The base class you have there is sufficient with the addition of getters. Implementing Comparable could prove valuable should you need to do sorting at some point.

With respect to "are there some methods I should have that I'm glossing over", that's really subjective and based the context in which the class is used. For example, if you never need to print the object, you may not need a 'toString()' function, but if you do, it might come in handy (especially if you want output formatted in a specific manner).

Java also has enum's, see here for a tutorial.

You might want to make subclasses for different games. PokerCard and SolitareCard can be Comparable; in one, Ace is greater than King; in the other, Ace is less than King.

For BlackjackCard, comparison is irrelevant. You might consider having an intValue(), where intValue() of K or Q or J is 10, but that won't work easily for BlackjackCard because an Ace can be one or eleven. So this is a good exercise in designing the model to match the real world: here is a problem where the integer value of the card is not completely intrinsic to the card but is dependent on the card's context.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top