有人可以指出这段代码的错误吗?这是一个卡重绘程序,但由于某种原因,一些卡重复

时间:2016-08-14 16:04:49

标签: java oop

public class redrawCards {

    final int MAX_CARDS = 52;
    int[] number = {1,2,3,4,5,6,7,8,9,10,11,12,13};
    char[] suit = {'D','H','S','C'};            //diamond,heart,spade,club
    String[] card = new String[MAX_CARDS];

    public redrawCards(){
        boolean finalize = false;
        for(int i = 0; i < MAX_CARDS; i++) {
            do{
                StringBuilder temp = new StringBuilder();
                boolean notFinal = false;
                int randomSuit = randomNumGenerator(4, 1); //creating random suits
                int randomNum = randomNumGenerator(13, 1); //creating random numbers

                temp.append(suit[randomSuit - 1]).append(number[randomNum - 1]);
                card[i] = temp.toString();

                System.out.println(i + ": " + card[i]);

                if(i > 1) {
                    for (int j = 0; j < i; j++) {
                        System.out.println("......" + card[i] + " " + card[j]);
                        if (card[i] == card[j]) {
                            notFinal = true;
                            System.out.println("000000");
                        }
                    }
                }
                if(!notFinal){
                    finalize = true;
                }
            }while (!finalize);
        }
        printAllCards();
    }

    private void printAllCards(){ 
        for(int i = 0; i < MAX_CARDS; i++){
            System.out.println(card[i]);
        }
    }

    private int randomNumGenerator(int upperBound, int lowerBound){
        return (lowerBound + (int)(Math.random() * ((upperBound - lowerBound) + 1)));
    }

    public static void main(String[] args){
        new redrawCards();
    }

}

1 个答案:

答案 0 :(得分:0)

为什么你这么复杂?您可以简单地创建一个List,遍历每个套装和编号,并将每个套件保存到List中。然后你可以调用Collections#shuffle方法并随意改变你的Card-Deck。如果你需要限制你的套牌,你可以在洗牌之后丢弃所有过多的牌。