Java Deck类

时间:2015-05-28 12:21:14

标签: java arrays

我有一个我正在制作的纸牌游戏的代码,我似乎无法让它输出甲板上的所有卡除了等级"A","2","3","8","J","Q""K"的卡(我不想要这些等级要输出)。请帮忙

import java.util.*;

public class Deck {

public static void main (String[]args) {

    String[]suit = {"♣","♥","♦","♠"} ;
    String[]rank = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"} ;

    int SUITS = suit.length;
    int RANKS = rank.length;
    int N = SUITS*RANKS;

 // initialize deck
    String[]deck = new String [N];

    for ( int i=0; i<RANKS; i++) {

        for (int j=0; j<SUITS; j++) {

            deck [SUITS*i+j] = rank[i] + suit[j];
        }
    }

 // shuffle
    for (int i=0; i<N; i++) {

        int r = i + (int)(Math.random()*(N-i));

        String t = deck [r];
        deck[r] = deck [i];
        deck[i] = t;
    }

// print shuffled deck
    for ( int i=0; i<N; i++) {

            System.out.println (deck[i]);

    }
 }
}

1 个答案:

答案 0 :(得分:0)

可能性是检查第一张卡是否是无效卡然后丢弃它并重新洗牌。就像Sara上面说的那样,我们会检查charAt索引0并查看它是否是无效卡。在下面的示例中,还有一种不同的方法可以对卡组进行混洗,以便可以在for循环中访问它。将这些东西留在顶部,但是给它一个机会。

deck = shuffleDeck(deck, N);

// print shuffled deck
for ( int i=0; i<N;) 
{

    //checking for invalid char at index 0
    if(i == 0 && (deck[i].charAt(0) == 'K' || deck[i].charAt(0) == 'A' || deck[i].charAt(0) == '2' || deck[i].charAt(0) == 'Q'))
    {
         System.out.println("Invalid first card.");
         shuffleDeck(deck, N);
    }
    else
    {
         System.out.println(deck[i]);
         i++;
    }
}
}

private static String[] shuffleDeck(String[] deck, int N)
{
    // shuffle
    for (int i=0; i<N; i++) 
    {
        int r = i + (int)(Math.random()*(N-i));
        String t = deck [r];
        deck[r] = deck [i];
        deck[i] = t;
    }
return deck;
}