Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

shuffling

 
J Borg
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 37
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . and welcome to the Ranch
 
J Borg
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you very much.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic