有没有一种方法可以确保我的数组不返回空值,或者有一种方法可以修复我的数组而不返回空值?

时间:2019-05-05 23:10:34

标签: java arrays null

我在创建随机卡片组时遇到问题。我的deck []返回空值,而卡片(例如“ 2 of Clubs”的“ 2C”)返回空值。我知道索引从0开始,这就是为什么您会看到“ int n = 51”的原因。我的错误来自按2的顺序创建牌组,而不是3的顺序。

公共类卡{

static String[] CARD = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
static String[] SUIT = {"C", "D", "H", "S"};

//creating a deck that is in order of C2-CA,D2-DA,H2-HA,S2-SA
public static String[] shuffledDeck() {
    int n=51;
    String[] deck = new String[n];
    for (int i = 0; i < CARD.length; i++) {
        for (int j = 0; j < SUIT.length; j++) {
            deck[(j+i)] = CARD[i] + SUIT[j];
        }
    }
    //Shuffling the deck
   for (int k = 0; k < n; k++) {
       int rand = k + (int) (Math.random() * (n - k));
       String temp = deck[k];
       deck[k] = deck[rand];
       deck[rand] = temp;
   }
   return deck;
}

公共类FiveCardPoker {

public static void main(String[] args)
{
    System.out.print(Arrays.toString(Cards.shuffledDeck()));
}

我希望看到一个随机的分类,例如“ [3C,8H,AD,9C等]” 但我得到的输出是“ [null,null,null,KC,null,null,10C等]”

2 个答案:

答案 0 :(得分:2)

我相信您的问题是由于您在创建过程中如何循环进行的,尤其是:

deck[(j+i)] = CARD[i] + SUIT[i]

这意味着您将有重复的索引。例如:

i = 0, j = 0 : i+j = 0
i = 0, j = 1 : i+j = 1
i = 0, j = 2 : i+j = 2
.
.
i = 1, j = 0 : i+j = 1
i = 1, j = 1 : i+j = 2
.
.
i = 2, j = 0 : i+j = 2

因此,某些索引将永远不会被设置,从而导致整个数组中的值为空。

您将需要为i和j查找公式,以给出正确的索引。

编辑: 还忘了提到您的数组应该以52的大小初始化,尽管您指出的最后一个索引仍然是51

答案 1 :(得分:0)

我可能迟到了,但是在这里:-

import java.util.Arrays;

class Cards {
    static String[] CARD = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", 
         "Q", "K", "A"};
    static String[] SUIT = {"C", "D", "H", "S"};

    public static String[] shuffledDeck() {
        int n = CARD.length * SUIT.length; // 13*4 = 52
        String[] deck = new String[n];
        int cnt = 0;
        for (int i = 0; i < CARD.length; ++i) {
            for (int j = 0; j < SUIT.length; ++j) {
                deck[cnt] = CARD[i] + SUIT[j];
                cnt++;
            }
        }

        for (int k = 0; k < n; k++) {
            int rand = k + (int) (Math.random() * (n - k));
            String temp = deck[k];
            deck[k] = deck[rand];
            deck[rand] = temp;
        }
        return deck;
    }
}

public class Program {
    public static void main(String[] args) {
        System.out.print(Arrays.toString(Cards.shuffledDeck()));
    }
}