Calling a Card from an Array of Cards

时间:2015-11-18 21:02:47

标签: java arrays if-statement methods

I am working on a Java experiment on creating a deck of cards and am having problems on one part. For this part, I have to have a method that takes an integer parameter and returns a Card object. It should return a referece to the card object in (0 to NUMBERS-1) in the deck array. If the index is not in range it must return null. I tried to do this by using deck[input parameter] but realized that that doesn't work because the deck is of Cards. I am unsure of how to go about this. What should I change to get this to work proper? Thanks!

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

3 个答案:

答案 0 :(得分:1)

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

您希望它返回Card而不是int

答案 1 :(得分:0)

我认为getCardAt应该返回一个Card对象(在给定的索引处)。因此,将其签名更改为public Card getCardAt(int number) {

答案 2 :(得分:0)

将public int getCardAt(int number)替换为:

公共卡getCardAt(int number)

此外,

您应该使用ArrayList作为deck变量。我想,你可以直接使用shuffle方法(所以你不必实现)。