在Java中向手添加卡片

时间:2018-12-10 22:36:10

标签: java

我正在制作有手牌的Player类,并且试图弄清楚如何向我的手牌添加。我有一个PlayingCard类和Dealer类,并且我知道我的添加纸牌方法应该类似于Dealer类中的Deal方法,但是我遇到了麻烦。

这是我的扑克牌课程,首先:

public class PlayingCard
{
  public enum Suit
  {
    Hearts, Clubs, Diamonds, Spades
  }

  public enum Rank
  {
    Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace
  }

  public final Suit suit;
  public final Rank rank;

  public PlayingCard(Rank rank, Suit suit)
  {
    this.rank = rank;
    this.suit = suit;
  }

  public String toString()
  {
    return this.rank.toString() + " of " + this.suit.toString();
  }
}

经销商等级:

import java.util.Random;

public class Dealer
{
  private PlayingCard[] deck;

  private int nextCard;

  public Dealer()
  {
    deck = openNewDeck();
  }

  public PlayingCard[] openNewDeck()
  {
    PlayingCard[] newDeck = new PlayingCard[52];

    int i = 0;

    for (PlayingCard.Suit s : PlayingCard.Suit.values())
    {

      for (PlayingCard.Rank r : PlayingCard.Rank.values())
      {

        newDeck[i] = new PlayingCard(r, s);

        i++;
      }
    }

    this.nextCard = 0;

    return newDeck;

  }

  public void shuffle(int i)
  {
    int j = i * 1000;

    for (j = 0; j <= 10000; j++)
    {

    for (i = 0; i <= 10; i++)
    {
      int k = (int)(Math.random() * deck.length);
      PlayingCard temp = deck[i];
      deck[i] = deck[k];
      deck[k] = temp;
    }
    }
  }

  public PlayingCard deal()
  {
    if (nextCard < deck.length)
    {
      return deck[nextCard++];
    }
    else
    { 
      System.out.println("No cards left!");
      return null;
    }
  }

  public String toString()
  {
    String c = "";
    for (int i = 0; i < 52; i++)
    {
      c += deck[i];
      if ((i+1)%1 == 0 || i == 51)
        c += "\n";
    }
    return c;
    }
  }

还有我困在Player类上的地方:

public class Player
{
  private PlayingCard[] hand;

  public final String name;

  public int nextCard;

  public Player(String name)
  {
    this.name = name;

    this.nextCard = 0;
  }

  public void receive(PlayingCard card)
  {
    if (nextCard < hand.length)
    {
      return hand[nextCard++];
    }
    else
    {
      System.out.println("Cannot add any more cards!");
    }
  }
}

1 个答案:

答案 0 :(得分:2)

在您的receive方法中,您没有向hand Array添加任何内容,而只是试图从hand返回一个元素。 (这是无效的,因为它是一个void方法,所以无效)而是将您传递的PlayingCard对象设置为索引:

public void receive(PlayingCard card)
{
    if (nextCard < hand.length)
    {
        hand[nextCard++] = card;
    }
    else
    {
        System.out.println("Cannot add any more cards!");
    }
}