需要确保卡片不会被挑选多次

时间:2017-02-25 02:40:27

标签: java

我正在开展一个项目,随机抽5张牌,告诉你手牌是什么样的。我已经完成了大部分工作,但是我似乎无法对其进行循环以确保它不会拉两次相同的卡。 (即我想确保它没有2颗心,3颗心,4颗钻石,4颗钻石,5颗黑桃)。

int[] value= new int[5];
int[] suit= new int[5];     
for (int i =0; i< value.length; i++) {
    card = rand.nextInt(13)+2;
    value[i]=card;
}
for (int k=0; k<suit.length; k++) {
    cardSuit = rand.nextInt(4)+1;
    suit[k]=cardSuit;
}
System.out.print("\nHere are your five cards");
for (int j=0; j<5;j++) {    
    System.out.print("\n"+value[j]+" of "+suit[j]); 
}

另外一件我遇到麻烦的事情就是我无法找到一种方法来正确地确保它会打印Hearts而不是1,Diamonds而不是2,依此类推。我一直在使用非常简单的东西,所以任何简单的评论都会非常感激。谢谢。

2 个答案:

答案 0 :(得分:1)

我会在绘制牌之前构建你的牌组。

// Use strings and pre-define our suit names.
String[] suit = { "Hearts", "Spades", "Clubs", "Diamonds" };
String[] face = new String[13];
String[] deck = new String[52];

// For the number of cards of a suit
for (int i = 1; i <= 13; i++) {
    // Set the value of the card face;
    String value = String.valueOf(i);
    // Replace the value for special cards
    if (i == 1 || i > 10) {
        switch(i) {
            case 11: value = "Jack";
                break;
            case 12: value = "Queen";
                break;
            case 13: value = "King";
                break;
            default: value = "Ace";
                break;
        }
    }

    // Set the face 2-10, Ace, Jack, Queen, King
    face[i-1] = value;
}

// For each suit
for (int s = 0; s < suit.length; s++) {
    // and each face value
    for (int f = 0; f < face.length; f++) {
        // add the face of that suit to the deck
        // (Ace, 2-10, Jack, Queen, King) of
        // (Hearts, Spades, Clubs, Diamonds)
        deck[(13*s)+f] = face[f] + " of " + suit[s];
    }
}

int[] handValue = new int[5];
int[] handSuit = new int[5];
int[] hand = new int[5];

// Draw 5 random cards
for( int h = 0; h < hand.length; h++ ) {
    int card = 0;
    do {
        // Do set card to a random number;
        card = rand.nextInt(52);
        // OR
        // If you want to be able to valuate the cards
        // store values separated for further calculation
        handValue[h] = rand.nextInt(13);
        handSuit[h] = rand.nextInt(4);
        card = handValue[h]*(handSuit[h]+1);
    } while (IntStream.of(hand).anyMatch(x -> x == card))
    // While the card is already in our hand
    hand[h] = card;
}

System.out.print("\nHere are your five cards");
for (int j=0; j<5; j++) {
    // Print the preformatted card value.
    System.out.print("\n" + deck[hand[j]]); 
}

答案 1 :(得分:0)

实现目标的一种方法是对值和套装使用相同的循环,以便您可以更轻松地检查重复。

for (int i =0; i< value.length; i++) {
    card = rand.nextInt(13)+2;
    cardSuit = rand.nextInt(4) +1;
    for(int j = 0; j <= i; j++){
         if(card == value[j]{
              card = rand.nextInt(13) + 2;
         }
         if(cardSuit == suit[j]{
              cardSuit = rand.nextInt(4) +1; 
         }
    }
    value[i]=card;
    suit[i]=cardSuit;
}