Java中纸牌的随机播放方法

时间:2018-11-29 20:01:48

标签: java

我正在制作一个PlayingCard类和一个Dealer类,该类使用Fisher-Yates混洗来洗牌。但是,我遇到了障碍,无法弄清楚我哪里出了问题。我在Dealer类中收到编译器错误“找不到符号:变量newDeck”。这是我的PlayingCard类,首先:

    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();
  }
}

这是我的Dealer类,在这里我得到了错误。我还试图让我的变量接受1-10之间的数字,这对应于重复循环将发生多少次,但是我也不认为我做得正确。

import java.util.Random;

public class Dealer
{
  private PlayingCard[] deck;

  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++;
      }
    }

    return newDeck;

  }

  public void shuffle(int i)
  {
    for (i = 0; i <= 10; i++)
    {
      int j = (int)(Math.random() * newDeck.length);
      int temp = newDeck[i];
      newDeck[i] = newDeck[j];
      newDeck[j] = temp;

      for (String p : newDeck)
      {
        System.out.println(p);
      }
    }
  }

  public String toString()
  {

  }

}

1 个答案:

答案 0 :(得分:4)

shuffle内,它们没有名为newDeck的变量。您要引用this.deck或仅引用deck来使用与Dealer实例关联的字段。