【问题标题】:Calling a Card from an Array of Cards从卡片数组中调用卡片
【发布时间】:2015-11-18 21:02:46
【问题描述】:

我正在进行一项关于创建一副纸牌的 Java 实验,但我遇到了一些问题。对于这一部分,我必须有一个接受整数参数并返回 Card 对象的方法。它应该返回对卡片组数组中(0 到 NUMBERS-1)中卡片对象的引用。如果索引不在范围内,它必须返回 null。 我试图通过使用甲板[输入参数] 来做到这一点,但意识到这不起作用,因为甲板是卡片。我不确定该怎么做。我应该改变什么才能让它正常工作? 谢谢!

public class DeckOfCards {
    public static final int NUMBERS = 52;
    public Card[] deck = new Card[NUMBERS];

    String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
    String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};

    public DeckOfCards() {
        int i = 0;
        for(String rank : ranks) {
            for(String suit : suits) {
                deck[i] = new Card(rank, suit);
                i++;
            }
        } 

    }

    public Random random = new Random();

    public void shuffle() {
        for(int i = 0; i < 500; i++) {
            int firstRandomCard = random.nextInt(NUMBERS - 1);
            int secondRandomCard = random.nextInt(NUMBERS - 1);

            Card firstCard = deck[firstRandomCard];
            Card secondCard = deck[secondRandomCard];

            deck[firstRandomCard] = secondCard;
            deck[secondRandomCard] = firstCard;

        }
    }

    //this is where I am having problems.
    public int getCardAt(int number) {
        if (number < 0 || number > NUMBERS - 1)
            return null;
        else 
            return deck[number];
    }  
}    

【问题讨论】:

标签: java arrays if-statement methods


【解决方案1】:

我认为您对getCardAt 方法的签名是错误的。

您希望它返回 Card 而不是 int

【讨论】:

    【解决方案2】:

    我认为getCardAt 应该返回一个 Card 对象(在给定的索引处)。所以,把它的签名改成public Card getCardAt(int number) {

    【讨论】:

      猜你喜欢
      • 2021-05-04
      • 2021-07-21
      • 2018-08-06
      • 2014-05-25
      • 1970-01-01
      • 2020-07-24
      • 2017-04-27
      • 2021-08-12
      • 2018-03-21
      相关资源
      最近更新 更多