I am having a tough time trying to create a "shuffleDeck()" method.
What I am trying to do is create a method that will take an array parameter (which will be the deck of cards) shuffle the cards, and return the shuffled array list.
This is the code:
class Card
{
int value;
String suit;
String name;
public String toString()
{
return (name + " of " + suit);
}
}
public class PickACard
{
public static void main( String[] args)
{
Card[] deck = buildDeck();
// display Deck(deck);
int chosen = (int)(Math.random()* deck.length);
Card picked = deck[chosen];
System.out.println("You picked a " + picked + " out of the deck.");
System.out.println("In Blackjack your card is worth " + picked.value + " points.");
}
public static Card[] buildDeck()
{
String[] suits = {"clubs", "diamonds", "hearts", "spades" };
String[] names = {"ZERO", "ONE", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "Jack", "Queen", "King", "Ace" };
int i = 0;
Card[] deck = new Card[52];
for ( String s: suits )
{
for ( int v = 2; v<=14; v++)
{
Card c = new Card();
c.suit = s;
c.name = names[v];
if ( v == 14)
c.value = 11;
else if ( v>10)
c.value = 10;
else
c.value = v;
deck[i] = c;
i++;
}
}
return deck;
}
public static String[] shuffleDeck( Card[] deck)
{
/** I have attempted to get two index numbers, and swap them.
I tried to figure out how to loop this so it kind of simulates "shuffling".
*/
}
public static void displayDeck( Card[] deck)
{
for ( Card c: deck)
{
System.out.println(c.value + "\t" + c);
}
}
}
I see two ways to do it:
-> You can use a shuffle algorithm like the Fisher-Yates shuffle algorithm if you want to implement yourself the method.
-> You can use the shuffle method from Collections
If this is for a school project (as I think it is), you might not be allowed to use built-in functions such as Collections::shuffle(). If this is the case, then you must try to simulate randomness (which in programming can be surprisingly hard).
The most common way to create a sense of randomness is to use an RNG (random number generator). As you said
Correct. One way to shuffle is to pick one card at a time and randomly select another card to swap the position with.
With these tools you can implement your own shuffle-function quite easily.
How about:
Or one-liner:
One way is to convert the array to a list, and use
java.util.Collections.shuffle(array)
to shuffle it:If you do still need an array instead of a List, you can add:
Here is a TIO (Try-it-online) link to see the array to list conversion and shuffling in action.
Code of the TIO copied below as reference: