4

As English is not my first language, i sometimes have trouble understanding a teacher's instructions as to what she wants. I will be providing the instruction of what she wants, the code i made, and my problem.

Instruction: • Has a private method to “shuffle” that creates a Queue with the 52 cards randomly shuffled. Use the Random Class.

My Code:

private void shuffling()
    {
        Random generator = new Random();  
        int[] cards = new int[52];  


        for (int i=0; i<cards.length; i++) 
        {
            cards[i] = i;
        }


        for (int i=0; i<cards.length; i++) 
        {
            int randomPosition = generator.nextInt(cards.length);
            int temp = cards[i];
            cards[i] = cards[randomPosition];
            cards[randomPosition] = temp;
        }
    }

Problem: Am i following my teacher's instruction correctly for what she wants? And if i am, my problem is, how do i create a queue with the 52 cards randomly shuffled? i have the shuffling part down i think. Any help would be appreciated.

With regards,

A novice programmer

user2128074
  • 193
  • 1
  • 1
  • 11
  • 2
    This is an okay way to shuffle the cards, but you still need to create the queue. So you could just loop through the array and add each one to a new queue – Ken Mar 03 '13 at 03:45
  • Thank you for your response, that is the part i had a problem with, i have read up on queues but still have no idea as to how to implement them here, would you be willing to give an example as to how to create a queue and then add each one to the queue? – user2128074 Mar 03 '13 at 03:50
  • One way is to make a linked list and just make your own functions for enqueue and dequeue – Ken Mar 03 '13 at 03:55

2 Answers2

3

The Queue part of the problem would entail creating an instance of some class that implements java.util.Queue.

Using the link to the Java API documentation that was (no doubt) provided in your lectures:

  • look up the Queue interface (@MaxOvrdrv has provided a link to an old version ... better to use the Java 7 javadocs ... go find them!)
  • look at the classes that implement Queue
  • read the descriptions of the classes
  • select one that will work in your use-case (i.e. a simple one)
  • read the Queue API methods and figure out what ones you need to use to add elements to a queue
  • code it ...

(I'm not going to provide you with links, because you need to know (and remember!) how to find them yourself.)


For the rest, well it depends on how you have been instructed to represent the "cards". If they are simply integers, then the rest of the code is reasonable. That's not a bad way to implement shuffling. (Random is not a good random number generator, but that hardly matters in this case.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

here's a link on how to create a queue in java:

How do I instantiate a Queue object in java?

Community
  • 1
  • 1
MaxOvrdrv
  • 1,780
  • 17
  • 32