我正在遇到一个创建随机牌卡的问题。我的甲板[]正在返回无效的值,例如" 2C",例如'两个俱乐部'以零为null。我知道索引从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等]"
我相信您的问题是由于您在创作上的循环方式,特别是:
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,如您所指出的
我可能迟到了,但是这里: -
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()));
}
}