Get the tools you need to learn Java skills fast!
Video tutorials, eBooks, hands-on lab exercises, sample code.
Get started
The moose likes Beginning Java and the fly likes shuffling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Software Craftsman this week in the Agile forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "shuffling" Watch "shuffling" New topic


J Borg

Joined: Jun 29, 2011
Posts: 2
I am trying to shuffle a deck of cards as follows however, my problem is that some of the numbers are being repeated. Any pointers what I am doing wrong please?

Daniel Marti
Ranch Hand

Joined: Jun 08, 2011
Posts: 37
To answer directly to your question, when you get a random card you are not making sure that the number chosen can't come out again.
To solve your problem while maintaining some of your structure, i would suggest you create an array with all cards, the mainDeck, and then create another array, the randDeck, by picking a card at random from mainDeck, passing it to randDeck and then removing it from mainDeck.

Now, to make it a lot easier to you (while still maintaining some structure), you can add all 52 numbers to a List <int>, or ArrayList<int> and then call Collections.shuffle() on it. More info on Collections here.

To make your code follow the guidelines of Object Oriented Programming, i would suggest creating a card class, with number and suite attributes, and work through there. It would be a lot easier in the long run.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 41593
. . . and welcome to the Ranch
J Borg

Joined: Jun 29, 2011
Posts: 2
thank you very much.
Have you tried LearnNowOnline?
subject: shuffling