deck of cards using methods and multiple classes - java

I'm getting no output and not sure where to go from here.
Design and implement a class called Card, which represents a standard playing card. Each card has a suit and a face value. Then, create a driver class that stores 52 objects of the Card class into an array. Include methods to shuffle the deck, deal a card and report the number of cards left in the deck. The shuffle method should assume a full deck. Your main method should deal each card from a shuffled deck, printing each card (suit and face value) as it is dealt.
Here's what I have so far:
import java.util.Random;
public class card {
public static void main(String[] args) {}
public class deck {
int[] deck = new int[52];
String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
public void create() {//initialize cards
for (int i = 0; i < deck.length; i++) deck[i] = i;
}
public void shuffle() {//deck shuffle
for (int i = 0; i < deck.length; i++) {
int index = (int) (Math.random() * deck.length);
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}
//display all the cards!
for (int i = 0; i < deck.length; i++)
{
String suit = suits[deck[i] / 13];
String rank = ranks[deck[i] % 13];
System.out.println("Card number " + deck[i] + ": " + rank + " of " + suit);
}
}
}
}

In java, the method main() is where your code will start running. You have nothing in your main method right now:
public static void main(String[] args) {}
To get it to do something, change it to something like this:
public static void main(String[] args) {
deck myDeck = new deck();
myDeck.create();
myDeck.shuffle();
}
As a note, it is good practice in java to name your classes with capital letters.

Here, I tried to write some code for you, its not complete, but provides a framework for you to continue, all you have to do is implement your own shuffle method and add more variables to ranks:
public class CardDriver {
public static void main(String[] args) {
Deck myDeck = new Deck();
myDeck.shuffle();
System.out.println("Dealt cards are:");
myDeck.dealAllCards();
}
}
class Card {
String suite, faceValue;
Card(String suite, String faceValue) {
this.suite = suite;
this.faceValue = faceValue;
}
void printCard() {
System.out.println(faceValue + " " + suite);
}
}
class Deck {
String[] suits = { "Spades", "Hearts", "Diamonds", "Clubs" };
String[] ranks = { "6", "7" };
int count = ranks.length * suits.length;
Card deck[] = new Card[count];
Deck() { // fills out the deck
int index = 0; // this is for simple deck filling
for (int i = 0; i < ranks.length; i++) { // for ranks
for (int j = 0; j < suits.length; j++) { // for suits
deck[index] = new Card(suits[j], ranks[i]);
index++;
}
}
};
void shuffle() { // shuffles the deck
// your code here
}
Card dealCard() { // gives card from deck
if (returnLeft() > 0) {
count--;
return deck[count];
} else return null;
}
int returnLeft() {
return count;
}
void dealAllCards() {
int counter = count;
for (int i = 0; i < counter; i++) {
Card someCard = dealCard();
someCard.printCard();
}
}
}

Related

Creating a discard pile for a card deck in java

So I only have one problem with my code and that is checking for the same card, because I do not want these cards to repeat. There is no reshuffling or whatsoever, its just random cards being dealt until there is none left. I have no clue on how to do it. Id appreciate some help; whether its theanswe or just a little nudge.
package Card;
import java.util.Random;
public class deckOfCards {
public String[] suite = { "Hearts", "Spade", "Diamonds", "Clubs" };
public String[] faceValue = { "Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };
public int deckCount = 0;
private Card[] deck = new Card[52];
public int index;
public void buildDeck() {
for (int i = 0; i < suite.length; i++) {
for (int j = 0; j < faceValue.length; j++) {
deck[deckCount] = new Card(suite[i], faceValue[j]);
deckCount++;
}
}
}
public Card shuffle(){
Random rand = new Random();
int index = rand.nextInt(52);
return deck[index];
}
}
this creates the card and randomizes them
package Card;
public class Card {
private String suite;
private String faceValue;
public Card(){
}
public Card(String suite, String faceValue){
this.setSuite(suite);
this.setFaceValue(faceValue);
}
public String getSuite(){
return suite;
}
//array list
//
public void setSuite(String suite){
this.suite = suite;
}
public String getFaceValue(){
return faceValue;
}
public void setFaceValue(String faceValue){
this.faceValue = faceValue;
}
}
package Card;
public class Driver {
public deckOfCards cards = new deckOfCards();
private Card [] discard = new Card[52];
public static void main(String[] args) {
Driver driver = new Driver();
driver.DealCards();
}
public void DealCards(){
int cardsLeft = 52;
cards.buildDeck();
Card randomCard = new Card();
for (int i = 0; i < 5; i++) {
cardsLeft--;
randomCard = cards.shuffle();
System.out.println(randomCard.getFaceValue() + " of " + randomCard.getSuite());
}
System.out.println("Cards left:" + cardsLeft);
}
}
this deals the cards. Again, any help is appreciated.
I think that what is missing is a method to remove a card from the deck.
Whenever a card is dealt, it needs to be removed, and a new random draw is performed on the remaining deck rather than on all 52 cards each time. This is called a draw without replacement. The current code performs a draw with replacement.
The quickest way to achieve this is to only modify the deckOfCards class:
Use a vector or cards rather than an array. This allows insertions and deletions. In an array, the size cannot be changed: a new array must be created every time, which is very inefficient.
In the shuffle function, instead of only returning a random card, you need to also remove it from the vector.
In the shuffle function, adapt 52 as the deck shrinks.

Pick four cards and compute their sum JAVA [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have most of my program, but I have hit the wall near the end, and I would love the help!
I have to write a program that picks four cards out of a deck of 52 and computes the sum. An Ace, King, Queen, and Jack represent 1, 13, 12, and 11 respectively. The program should display the number of pick that yields the sum of 24.
What I have so far:
public class Exercise07_29 {
public static void main(String[] args){
//initialize everything
int[] deck = new int[52];
String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
//initialize the cards
for(int i = 0; i< deck.length; i ++)
deck[i] = i;
//shuffle the cards
for(int i = 0; i < deck.length; i++){
//generate an index randomly
int index = (int)(Math.random() * deck.length);
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}
//display the four cards
for(int i = 0; i < 4; i++){
String suit = suits[deck[i] / 13];
String rank = ranks[deck[i] % 13];
System.out.println(rank + " of " + suit);
}
//initialize Ace Jack Queen King
int Ace, Jack, Queen, King;
//Assign a point vale to each
int[] points = {Ace = 1, Jack = 11, Queen = 12, King = 13};
//add the cards together and show output
}
}
I tried a loop for the addition, but am having trouble when it comes to adding a random output together....
Any and all help would be greatly appreciated! :)
import java.util.*;
public class Exercise07_29 {
public static void main(String[] args){
//initialize everything
int[] deck = new int[52];
String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
List<String> pickedCards = new ArrayList<String>();
//initialize the cards
for(int i = 0; i< deck.length; i ++)
deck[i] = i;
//shuffle the cards
for(int i = 0; i < deck.length; i++){
//generate an index randomly
int index = (int)(Math.random() * deck.length);
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}
//display the four cards
for(int i = 0; i < 4; i++){
String suit = suits[deck[i] / 13];
String rank = ranks[deck[i] % 13];
System.out.println(rank + " of " + suit);
pickedCards.add(rank);
}
//initialize Ace Jack Queen King
int Ace, Jack, Queen, King;
//Assign a point vale to each
int[] points = {Ace = 1, Jack = 11, Queen = 12, King = 13};
//add the cards together and show output
int sum = 0;
int jack = 11;
int queen = 12;
int king = 13;
int ace = 1;
Iterator<String> iterator = pickedCards.iterator();
while(iterator.hasNext()) {
String rank = iterator.next();
System.out.println(rank);
if(rank.equalsIgnoreCase("Jack")){
sum = sum+jack;
}
else if(rank.equalsIgnoreCase("Queen")){
sum = sum+queen;
}
else if(rank.equalsIgnoreCase("King")){
sum = sum+king;
}
else if(rank.equalsIgnoreCase("Ace")){
sum = sum+ace;
}
else {
sum = sum+Integer.parseInt(rank);
}
}
System.out.println("Sum of picked cards is : "+sum);
}
}
I am not sure what is your problem here. If it is that you are wondering how to map the Ace, Jack, Queen and King to points then I would suggest the following.
Map<Integer, String> cardToPoints = new HashMap<Integer, String>();
cardToPoints.add(1, "Ace");
cardToPoints.add(11, "Jack");
cardToPoints.add(12, "Queen");
cardToPoints.add(13, "King");
Then if you need to print the text just search for the number in the map and if there is entry print it otherwise print the number you have.
As variation to this you can create class Card containing points for the card and it string representation and fill the map with this cards.
For example:
cardPoints.add(1, new Card(1, "Ace of Spades");
....
cardPoints.add(14, new Card(1, "Ace of Hearts");
cardPoints.add(15, new Card(2, "2 of Hearts");
Then just get the card from the map get the points and sum + print the exact cards. Easy and clean( apart of the 52 entries for the map initilization );
Java's an object-oriented language. You're probably a beginner, but here's an example for you to think about.
package cards;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Exercise07_29
* #author Michael
* #link https://stackoverflow.com/questions/31639964/pick-four-cards-and-compute-their-sum-java
* #since 7/26/2015 1:42 PM
*/
public class Exercise07_29 {
public static final int NUM_CARDS = 4;
public static void main(String[] args) {
Deck deck = new Deck();
List<Card> hand = new ArrayList<>();
int score = 0;
for (int i = 0; i < NUM_CARDS; ++i) {
Card card = deck.deal();
hand.add(card);
score += card.getRank().getValue();
}
System.out.println(hand);
System.out.println(score);
}
}
enum SUIT {
CLUB, DIAMOND, HEART, SPADE;
}
enum RANK {
ACE(1), TWO(2), THREE(3), FOUR(4), FIVE(5), SIX(6), SEVEN(7), EIGHT(8), NINE(9), TEN(10), JACK(11), QUEEN(12), KING(13);
private final int value;
RANK(int value) { this.value = value; }
public int getValue() {
return value;
}
}
class Card implements Comparable<Card> {
private final SUIT suit;
private final RANK rank;
public Card(SUIT suit, RANK rank) {
if (suit == null) throw new IllegalArgumentException("suit cannot be null");
if (rank == null) throw new IllegalArgumentException("rank cannot be null");
this.suit = suit;
this.rank = rank;
}
public SUIT getSuit() {
return suit;
}
public RANK getRank() {
return rank;
}
#Override
public int compareTo(Card other) {
if (this.getRank().equals(other.getRank())) {
return this.getSuit().compareTo(other.getSuit());
} else {
return this.getRank().getValue() - other.getRank().getValue();
}
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Card card = (Card) o;
return suit == card.suit && rank == card.rank;
}
#Override
public int hashCode() {
int result = suit.hashCode();
result = 31 * result + rank.hashCode();
return result;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Card{");
sb.append("suit=").append(suit);
sb.append(", rank=").append(rank);
sb.append('}');
return sb.toString();
}
}
class Deck {
private List<Card> deck;
private Random random;
public Deck() {
this.init();
this.random = new Random();
}
public Deck(long seed) {
this.init();
this.random = new Random(seed);
}
private void init() {
this.deck = new ArrayList<Card>();
for (SUIT suit: SUIT.values()) {
for (RANK rank: RANK.values()) {
this.deck.add(new Card(suit, rank));
}
}
}
public Card deal() { return this.deal(true); }
public Card deal(boolean removeCard) {
int value = this.random.nextInt(this.deck.size());
return removeCard ? this.deck.remove(value) : this.deck.get(value);
}
}

Deck of cards JAVA

I have created my deck of cards that deals every card and a suit until there is no card remaining. For my project, I need to split it up into 3 classes which includes a driver class. I first created one class with everything so I knew how to make it all work.
public class DeckOfCards2 {
public static void main(String[] args) {
int[] deck = new int[52];
String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
// Initialize cards
for (int i = 0; i < deck.length; i++) {
deck[i] = i;
}
// Shuffle the cards
for (int i = 0; i < deck.length; i++) {
int index = (int)(Math.random() * deck.length);
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
}
// Display the all the cards
for (int i = 0; i < 52; i++) {
String suit = suits[deck[i] / 13];
String rank = ranks[deck[i] % 13];
System.out.println( rank + " of " + suit);
}
}
}
Now trying to split it up into 3 classes. I am getting red sqiggle lines on ALL my deck/suit variables on my DeckOfCards class. I dont know how to fix it.
public class DeckOfCards {
private Card theCard;
private int remainingCards = 52;
DeckOfCards() {
theCard = new Card();
}
public void shuffle(){
for (int i = 0; i < deck.length; i++) {
int index = (int)(Math.random() deck.length);
int temp = deck[i];
deck[i] = deck[index];
deck[index] = temp;
remainingCards--;
}
}
public void deal(){
for (int i = 0; i < 52; i++) {
String suit = suits[deck[i] / 13];
String rank = ranks[deck[i] % 13];
System.out.println( rank + " of " + suit);
System.out.println("Remaining cards: " + remainingCards);
}
}
}
Card class:
public class Card {
int[] deck = new int[52];
String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
Card() {
for (int i = 0; i < deck.length; i++) {
deck[i] = i;
}
}
}
Dealer class
public class Dealer {
public static void main(String[]args){
System.out.println("The deck will randomly print out a card from a full deck each time");
DeckOfCards player = new DeckOfCards();
player.deal();
}
}
As somebody else already said, your design is not very clear and Object Oriented.
The most obvious error is that in your design a Card knows about a Deck of Cards. The Deck should know about cards and instantiate objects in its constructor. For Example:
public class DeckOfCards {
private Card cards[];
public DeckOfCards() {
this.cards = new Card[52];
for (int i = 0; i < ; i++) {
Card card = new Card(...); //Instantiate a Card
this.cards[i] = card; //Adding card to the Deck
}
}
Afterwards, if you want you can also extend Deck in order to build different Deck of Cards (for example with more than 52 cards, Jolly etc.). For Example:
public class SpecialDeck extends DeckOfCards {
....
Another thing that I'd change is the use of String arrays to represent suits and ranks. Since Java 1.5, the language supports Enumeration, which are perfect for this kind of problems. For Example:
public enum Suits {
SPADES,
HEARTS,
DIAMONDS,
CLUBS;
}
With Enum you get some benefits, for example:
1) Enum is type-safe you can not assign anything else other than predefined Enum constants to an Enum variable. For Example, you could write your Card's constructor as following:
public class Card {
private Suits suit;
private Ranks rank;
public Card(Suits suit, Ranks rank) {
this.suit = suit;
this.rank = rank;
}
This way you are sure to build consistent cards that accept only values ​​of your enumeration.
2) You can use Enum in Java inside Switch statement like int or char primitive data type (here we have to say that since Java 1.7 switch statement is allowed also on String)
3) Adding new constants on Enum in Java is easy and you can add new constants without breaking existing code.
4) You can iterate through Enum, this can be very helpful when instantiating Cards. For Example:
/* Creating all possible cards... */
for (Suits s : Suits.values()) {
for (Ranks r : Ranks.values()) {
Card c = new Card(s,r);
}
}
In order to not invent again the wheel, I'd also change the way you keep Cards from array to a Java Collection, this way you get a lot of powerful methods to work on your deck, but most important you can use the Java Collection's shuffle function to shuffle your Deck. For example:
private List<Card> cards = new ArrayList<Card>();
//Building the Deck...
//...
public void shuffle() {
Collections.shuffle(this.cards);
}
This is my implementation:
public class CardsDeck {
private ArrayList<Card> mCards;
private ArrayList<Card> mPulledCards;
private Random mRandom;
public enum Suit {
SPADES,
HEARTS,
DIAMONDS,
CLUBS;
}
public enum Rank {
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING,
ACE;
}
public CardsDeck() {
mRandom = new Random();
mPulledCards = new ArrayList<Card>();
mCards = new ArrayList<Card>(Suit.values().length * Rank.values().length);
reset();
}
public void reset() {
mPulledCards.clear();
mCards.clear();
/* Creating all possible cards... */
for (Suit s : Suit.values()) {
for (Rank r : Rank.values()) {
Card c = new Card(s, r);
mCards.add(c);
}
}
}
public static class Card {
private Suit mSuit;
private Rank mRank;
public Card(Suit suit, Rank rank) {
this.mSuit = suit;
this.mRank = rank;
}
public Suit getSuit() {
return mSuit;
}
public Rank getRank() {
return mRank;
}
public int getValue() {
return mRank.ordinal() + 2;
}
#Override
public boolean equals(Object o) {
return (o != null && o instanceof Card && ((Card) o).mRank == mRank && ((Card) o).mSuit == mSuit);
}
}
/**
* get a random card, removing it from the pack
* #return
*/
public Card pullRandom() {
if (mCards.isEmpty())
return null;
Card res = mCards.remove(randInt(0, mCards.size() - 1));
if (res != null)
mPulledCards.add(res);
return res;
}
/**
* Get a random cards, leaves it inside the pack
* #return
*/
public Card getRandom() {
if (mCards.isEmpty())
return null;
Card res = mCards.get(randInt(0, mCards.size() - 1));
return res;
}
/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* #param min Minimum value
* #param max Maximum value. Must be greater than min.
* #return Integer between min and max, inclusive.
* #see java.util.Random#nextInt(int)
*/
public int randInt(int min, int max) {
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = mRandom.nextInt((max - min) + 1) + min;
return randomNum;
}
public boolean isEmpty(){
return mCards.isEmpty();
}
}
Here is some code. It uses 2 classes (Card.java and Deck.java) to accomplish this issue, and to top it off it auto sorts it for you when you create the deck object. :)
import java.util.*;
public class deck2 {
ArrayList<Card> cards = new ArrayList<Card>();
String[] values = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
String[] suit = {"Club", "Spade", "Diamond", "Heart"};
static boolean firstThread = true;
public deck2(){
for (int i = 0; i<suit.length; i++) {
for(int j=0; j<values.length; j++){
this.cards.add(new Card(suit[i],values[j]));
}
}
//shuffle the deck when its created
Collections.shuffle(this.cards);
}
public ArrayList<Card> getDeck(){
return cards;
}
public static void main(String[] args){
deck2 deck = new deck2();
//print out the deck.
System.out.println(deck.getDeck());
}
}
//separate class
public class Card {
private String suit;
private String value;
public Card(String suit, String value){
this.suit = suit;
this.value = value;
}
public Card(){}
public String getSuit(){
return suit;
}
public void setSuit(String suit){
this.suit = suit;
}
public String getValue(){
return value;
}
public void setValue(String value){
this.value = value;
}
public String toString(){
return "\n"+value + " of "+ suit;
}
}
Very Simple code to generate deck off Card:
class Card{
private final String suit;
private final String rank;
public Card(String suit, String rank){
this.suit = suit;
this.rank = rank;
}
#Override
public String toString() {
return "Card [suit=" + suit + ", rank=" + rank + "]";
}
}
class DeckOfCard{
private static final String suits[] = {"club", "diamond", "heart", "spade"};
private static final String ranks[] = {null,"ace", "deuce", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king"};
private final ArrayList<Card> cards;
public DeckOfCard(){
cards = new ArrayList<Card>();
for (int i = 0; i<suits.length; i++) {
for(int j=0; j<ranks.length; j++){
this.cards.add(new Card(suits[i],ranks[j]));
}
}
//Shuffle after the creation
Collections.shuffle(this.cards);
}
public ArrayList<Card> getCards() {
return cards;
}
}
public class CardPuzzle {
public static void main(String[] args) {
DeckOfCard deck = new DeckOfCard();
ArrayList<Card> cards = deck.getCards();
for(Card card:cards){
System.out.println(card);
}
}
}
There is something wrong with your design. Try to make your classes represent real world things. For example:
The class Card should represent one card, that is the nature of a "Card". The Card class does not need to know about Decks.
The Deck class should contain 52 Card objects (plus jokers?).
First you have an architectural issue with your classes. You moved the property deck inside your class Card. But of couse it is a property of the card deck and thus has to be inside class DeckOfCards. The initialization loop should then not be in the constructor of Card but of your deck class. Moreover, the deck is an array of int at the moment but should be an array of Cards.
Second, inside method Deal you should refer to suits as Card.suits and make this member static final. Same for ranks.
And last, please stick to naming conventions. Method names are always starting with a lower case letter, i.e. shuffle instead of Shuffle.
There are many errors in your code, for example you are not really calling your deck by just typing deck in your Shuffle method. You can only call it by typing theCard.deck
I have changed your shuffle method:
public void Shuffle(){
for (int i = 0; i < theCard.deck.length; i++) {
int index = (int)(Math.random()*theCard.deck.length );
int temp = theCard.deck[i];
theCard.deck[i] = theCard.deck[index];
theCard.deck[index] = temp;
remainingCards--;
}
}
Also, as it is said you have structural problem. You should name classes as you understand in real life, for example, when you say card, it is only one card, when you say deck it is supposed to be 52+2 cards. In this way your code would be more understandable.
There is a lot of error in your program.
Calculation of index. I think it should be Math.random()%deck.length
In the display of card. According to me, you should make a class of card which has rank suit and make the array of that class type
If you want I can give you the Complete structure of that but it is better if u make it by yourself
I think the solution is just as simple as this:
Card temp = deck[cardAindex];
deck[cardAIndex]=deck[cardBIndex];
deck[cardBIndex]=temp;
public class shuffleCards{
public static void main(String[] args) {
String[] cardsType ={"club","spade","heart","diamond"};
String [] cardValue = {"Ace","2","3","4","5","6","7","8","9","10","King", "Queen", "Jack" };
List<String> cards = new ArrayList<String>();
for(int i=0;i<=(cardsType.length)-1;i++){
for(int j=0;j<=(cardValue.length)-1;j++){
cards.add(cardsType[i] + " " + "of" + " " + cardValue[j]) ;
}
}
Collections.shuffle(cards);
System.out.print("Enter the number of cards within:" + cards.size() + " = ");
Scanner data = new Scanner(System.in);
Integer inputString = data.nextInt();
for(int l=0;l<= inputString -1;l++){
System.out.print( cards.get(l)) ;
}
}
}
import java.util.List;
import java.util.ArrayList;
import static java.lang.System.out;
import lombok.Setter;
import lombok.Getter;
import java.awt.Color;
public class Deck {
private static #Getter List<Card> deck = null;
final int SUIT_COUNT = 4;
final int VALUE_COUNT = 13;
public Deck() {
deck = new ArrayList<>();
Card card = null;
int suitIndex = 0, valueIndex = 0;
while (suitIndex < SUIT_COUNT) {
while (valueIndex < VALUE_COUNT) {
card = new Card(Suit.values()[suitIndex], FaceValue.values()[valueIndex]);
valueIndex++;
deck.add(card);
}
valueIndex = 0;
suitIndex++;
}
}
private enum Suit{CLUBS("Clubs", Color.BLACK), DIAMONDS("Diamonds", Color.RED),HEARTS("Hearts", Color.RED), SPADES("Spades", Color.BLACK);
private #Getter String name = null;
private #Getter Color color = null;
Suit(String name) {
this.name = name;
}
Suit(String name, Color color) {
this.name = name;
this.color = color;
}
}
private enum FaceValue{ACE(1), TWO(2), THREE(3),
FOUR(4), FIVE(5), SIX(6), SEVEN(7), EIGHT (8), NINE(9), TEN(10),
JACK(11), QUEEN(12), KING(13);
private #Getter int cardValue = 0;
FaceValue(int value) {
this.cardValue = value;
}
}
private class Card {
private #Getter #Setter Suit suit = null;
private #Getter #Setter FaceValue faceValue = null;
Card(Suit suit, FaceValue value) {
this.suit = suit;
this.faceValue = value;
}
public String toString() {
return getSuit() + " " + getFaceValue();
}
public String properties() {
return getSuit().getName() + " " + getFaceValue().getCardValue();
}
}
public static void main(String...inputs) {
Deck deck = new Deck();
List<Card> cards = deck.getDeck();
cards.stream().filter(card -> card.getSuit().getColor() != Color.RED && card.getFaceValue().getCardValue() > 4).map(card -> card.toString() + " " + card.properties()).forEach(out::println);
}
}

How to deal 4 hands of 10 cards with a deck?

So I have the code for a deck, but I dont know how to make another class to deal 4 hands of 10 cards each. The other class should print on the screen, in text, 4 hands of 10 random cards. Can someone show me the code on how to accomplish this? Im using blueJ aswell.
Below is my code for the deck:
public class Card
{
public static void main(String[] args)
{
String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace" };
int SUITS = suit.length;
int RANKS = rank.length;
int N = SUITS * RANKS;
// initialize deck
String[] deck = new String[N];
for (int i = 0; i < RANKS; i++) {
for (int j = 0; j < SUITS; j++) {
deck[SUITS*i + j] = rank[i] + " of " + suit[j];
}
}
// shuffle the deck
for (int i = 0; i < N; i++) {
int r = i + (int) (Math.random() * (N-i));
String t = deck[r];
deck[r] = deck[i];
deck[i] = t;
}
for (int i = 0; i < N; i++) {
System.out.println(deck[i]);
}
}
}
In the spirit of the game, let's create a hierarchy for handling could work. The largest scope will be the Game, which will delegate the actions to the other classes. We will also have 3 classes: Deck, Dealer, Player.
A Game will have a Dealer, and an ArrayList of Player
A Dealer will have a Deck
A Player will have an ArrayList of String indicating your cards
A Game can then tell a dealer to create and shuffle a deck. You can call a dealCards passing the Players as a param to the dealer who can, based on the number of players, give them the next element in the Deck, and remove that element from the deck.
Once you have dealt all the cards, the game can then tell the players to show their hands, printing the results.
public Dealer{
private Deck deck;
....
public void shuffleDeck(){...}
public void dealCards(List<Player> players){ ...}
}
public Player{
private List<String> hand;
....
public void addToHand(String card){....}
}
Your Card / Deck class should be broken up into two classes.
A Card class would describe a card.
public class Card {
private String rank;
private String suit;
public Card(String rank, String suit) {
this.rank = rank;
this.suit = suit;
}
public String getRank() {
return rank;
}
public String getSuit() {
return suit;
}
#Override
public String toString() {
return rank + " of " + suit;
}
}
A Deck class describes a deck of cards.
public class Deck {
private String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9",
"10", "Jack", "Queen", "King", "Ace" };
private String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
private Card[] cards;
public Deck() {
cards = new Card[suit.length * rank.length];
for (int i = 0; i < rank.length; i++) {
for (int j = 0; j < suit.length; j++) {
cards[suit.length * i + j] = new Card(rank[i], suit[j]);
}
}
}
public Card[] shuffleDeck() {
for (int i = 0; i < cards.length; i++) {
int r = (int) (Math.random() * (cards.length - 1));
Card t = cards[r];
cards[r] = cards[i];
cards[i] = t;
}
return cards;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < cards.length; i++) {
builder.append(cards[i].toString());
builder.append(System.getProperty("line.separator"));
}
return builder.toString();
}
}
Until you understand how these two classes work together, there's no point introducing other classes.
The point of Java, or any object oriented computer language, is to break up your problem into smaller classes that each do one thing and do it well.

I need help drawing a Hand of Cards

I am trying to draw a Hand of Cards (in the Hand class) but have it shuffled. My problem is if I do shuffleDeck() in the initialDeal() method (where I need to draw a Hand of Cards but shuffled) it gives me an ArrayIndexOutOfBounds exception.
And I draw two narfs OF Clubs... Note, the narf is basically 0 and just a placeholder. It will not be used.
class Card {
int suit, rank;
public Card () {
this.suit = 0; this.rank = 0;
}
public Card (int suit, int rank) {
this.suit = suit; this.rank = rank;
}
public int getSuit() {
return suit;
}
public int getRank() {
return rank;
}
public void printCard () {
String[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
String[] ranks = { "narf", "Ace", "2", "3", "4", "5", "6",
"7", "8", "9", "10", "Jack", "Queen", "King" };
System.out.println (ranks[rank] + " of " + suits[suit]);
} //end printCard
} //end class
Card class(this is basically doing basic stuff) ^
import java.util.Random;
class Hand {
static Card[] deck = new Card[52];
Card[] hand = new Card[10];
static int index;
public static void createDeck () {
int m = 0;
for (int j = 0; j < 4; j++) {
for (int k = 1; k < 14; k++) {
deck[m] = new Card(j,k);
m++;
}
}
index = 0;
} // end createDeck
public static Card deal () {
Hand.index++;
return deck[index-1];
} // end deal
public static int compareCard (Card c1, Card c2) {
if (c1.getSuit() > c2.getSuit()) return 1;
if (c1.getSuit() < c2.getSuit()) return -1;
if (c1.getRank() > c2.getRank()) return 1;
if (c1.getRank() < c2.getRank()) return -1;
return 0;
} // end compareCard
public void printDeck (int size) {
int j = 0;
while (j < size) {
deck[j].printCard();
j++;
}
}// end printDeck
public static void shuffleDeck () {
Card tempCard;
Random rd = new Random();
for (index = 0; index < deck.length; index++) {
int r = rd.nextInt(deck.length);
tempCard = deck[index];
deck[index] = deck[r];
deck[r] = tempCard;
}
} // end shuffleDeck
public void initialDeal() {
hand[0] = null;
hand[1] = null;
hand[0] = deal();
hand[1] = deal();
}
public void printHand() {
initialDeal();
index = 0;
for(Card outputCard = new Card(); hand[index] != null; index++) {
outputCard.printCard();
}
}
}
Hand class^ (this is where I need to draw two cards from a shuffled deck)
class Dealer {
Hand dealer = new Hand();
public Dealer () {
dealer.createDeck();
dealer.shuffleDeck();
System.out.println("Dealer's Hand");
System.out.println("");
initDeal();
}
public void initDeal() {
dealer.initialDeal();
dealer.printHand();
}
} //end class
Dealer class.^ Calling the methods of Hand
class Driver {
public static void main (String[] args) {
Dealer dealer = new Dealer();
} //end main method
} //end class
^ Running everything basically
You're modifying the index in shuffleDeck, so after the shuffleDeck finishes, the index is shuffleDeck.length.
In shuffleDeck, do for (int index = 0; index < deck.length; index++)
(note the int index -> declare local variable, and not use the static one.)
Or you can (in initialDeal) set the index to 0.

Categories

Resources