Reputation: 13
So I am a beginner in programming and I have a project in class that asks me to make a bridge hand and deal them out to four players. One of the tasks asks me to print out a shuffled deck, however, when I try to print it out, it outputs 52 null statements instead of the shuffled deck. Can someone please help me figure this out. Thank you.
import java.util.*;
public class Card {
public static String[] SUITS = {"Clubs","Diamonds","Hearts","Spades"};
public static String[] RANKS = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
public static String[]deck = new String[52];
public static String[] createDeck() { // initializes and creates deck
for(int i = 0; i < RANKS.length ; i++) {
for(int j = 0; j < SUITS.length ; j++) {
deck[SUITS.length * i + j] = RANKS[i] + " of " + SUITS[j];
}
}
return deck;
}
public static void shuffleDeck(String[]deck) { //shuffles deck created from array
int n = deck.length;
for (int i = 0; i < n; i++) {
int r = i + (int)(Math.random() * (n-i));
String temp = deck[r];
deck[r] = deck[i];
deck[i] = temp;
System.out.println(deck[i]);
}
}
public static void main(String[] args) {
Card.shuffleDeck(deck);
}
Upvotes: 1
Views: 71
Reputation: 3866
You are missing a createDeck()
call in your main()
method:
public static void main(String[] args) {
createDeck();
shuffleDeck(deck);
}
Because the following statement only initializes the deck
array with 52
null
values:
public static String[]deck = new String[52];
You need to fill the deck
array with actual values to display them properly. And you can safely mark createDeck()
as void
because you don't need to return deck
array as it is declared as static
which will be accessible anyway. Same is the case with shuffleDeck()
method, you don't need to pass the static
array, it will be accessible.
Or you could go with another approach in which deck
array is declared as a local variable and it is passed to these methods as an argument.
Upvotes: 1