如何在循环中洗牌并打印它们

时间:2016-09-27 20:40:09

标签: java

您好我试图随意洗牌并打印" top"四张牌和我的老师告诉我要将洗牌循环视为交换,但我不确定我是否正确。任何帮助将不胜感激。

 public static void main(String[] args) 
{
   //Random number generator for shuffle 

    Random rand = new Random();

   //Explaining the program

   System.out.println("This program is meant to create a deck of cards and to show the top 4 cards");

   //All Arrays

   int [] deck = new int [52];
   String [] suits = new String []{"Hearts, Spades, Clubs, Diamonds"};
   String [] faceValue = new String []{"Ace, 2,3,4,5,6,7,8,9,10, Jack, Queen, King"};

   //Filling the deck

   for(int index = 0; index < deck.length; index ++)
   {
       deck[index] = index+1;
       //System.out.println(deck[index]);
   }

   //Shuffle the deck

    for(int i =0; i<deck.length; i ++)
   {
       int temp = rand.nextInt(51)+1;
       deck[i] = temp;
       deck[i] = deck[temp];
       deck[i] = temp;
       //System.out.println(deck[i]);


   }
    //Display
   for(int index = 0; index<4;index++)
   {
       String suit;
       String face;
       suit = suits[deck[index]/13];
       face= faceValue[deck[index]%13];
       System.out.println("Your cards are:\n");


   }

2 个答案:

答案 0 :(得分:0)

int temp = rand.nextInt(51)+1;
deck[i] = temp;
deck[i] = deck[temp];
deck[i] = temp;

这不会改变任何事情。它甚至不使用数组的元素作为最终的数组元素。

使用

可以达到相同的效果
deck[i] = rand.nextInt(51)+1;

而不是 - 无论你在这个循环中尝试做什么,你应该像这样解决问题:

for i = deck.length-1, deck.length-2, ..., 2, 1
    select j uniformly at random from 0, 1, ..., i-1, i
    swap elements at indices j and i

这种方式在循环迭代之后,您已选择索引>=i处的元素,并且您只考虑后续迭代中的其余元素

或在java代码中:

for (int i = deck.length-1; i > 0; i--) {
    int j = rand.nextInt(i+1);
    int temp = deck[i];
    deck[i] = deck[j];
    deck[j] = temp;
}

此外请注意,如果您按照以下方式初始化套牌,则打印阵列可能会失败:

for(int index = 0; index < deck.length; index ++)
{
   deck[index] = index+1;
}

如果最后一个元素是改组后的前4个元素之一,则使用4 = 52/13作为suits数组的索引,这将导致ArrayIndexOutOfBoundsException

相反,你需要像这样初始化索引:

for(int index = 0; index < deck.length; index++) {
   deck[index] = index;
}

此外,您使用包含单个字符串的数组,而不是使用包含多个元素的数组:

String [] suits = new String []{"Hearts", "Spades", "Clubs", "Diamonds"};
String [] faceValue = new String []{"Ace", "2","3","4","5","6","7","8","9","10", "Jack", "Queen", "King"};

答案 1 :(得分:0)

要交换两个值,您必须执行此操作:

temp = a;
a = b;
b = temp;

因此,在您的情况下,您应该有两个临时变量 - temprandrand将表示将与当前卡交换的卡片索引。

int rand = rand.nextInt(51) + 1;
temp = deck[i];
deck[i] = deck[rand];
deck[i] = temp;