I'm very new to Java and I'm having trouble understanding how to shuffle an array (or my deck array). I've tried using the Random class, but it's not doing the thing for me. Anyway, here go the classes I've created:
CardGame
import java.util.Random;
public class CardGame {
public static void main(String[] args) {
// final int SPADES = 0, HEARTS = 1, DIAMONS = 2, CLUBS = 3;
final int ACE = 1, TWO = 2, THREE = 3, FOUR = 4, FIVE = 5, SIX = 6, SEVEN = 7, EIGHT = 8;
final int NINE = 9, TEN = 10, JACK = 11, QUEEN = 12, KING = 13;
Random rand = new Random();
int[][] deck = {
{ ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING },
player1.setHand(deck[i][randIndex]);
player2.setHand(deck[i][randIndex]);
player3.setHand(deck[i][randIndex]);
}
}
System.out.println(player1.getHand());
System.out.println(player2.getHand());
System.out.println(player3.getHand());
}
}
Player
public class Player {
final int MAX_HAND = 6;
private String playerName;
private int playerHand[] = new int[MAX_HAND];
public Player(String name) {
playerName = name;
}
public void setHand(int card) {
int currentLength = playerHand.length;
if (currentLength == MAX_HAND) {
return;
}
playerHand[currentLength] = card;
}
public String getHand() {
String cardN
case 8: cardNames += "Eight"; break;
case 9: cardNames += "Nine"; break;
case 10: cardNames += "Ten"; break;
case 11: cardNames += "Jack"; break;
case 12: cardNames += "Queen"; break;
case 13: cardNames += "King"; break;
}
if (i < playerHand.length - 2) {
cardNames += ", ";
}
}
return playerName + " has " + cardNames + " on his hand.";
}
}
The result is always:
Name1 has Ace, Two, Three, Four and Five on his hand.
Name2 has Ace, Two, Three, Four and Five on his hand.
Name3 has Ace, Two, Three, Four and Five on his hand.
What is it that I'm doing wrong to generate a random index for the inner array of deck?
Thank you.
Replace switch (i) with switch (playerHand[i]) in your getHand() method and also call nextInt() for every player not just once on each iteration.
Change setHand() into
int index = 0;
public void addCard(int card) {
if (index == MAX_HAND) {
return;
}
playerHand[index++] = card;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With