Results 1 to 3 of 3
- 12-12-2010, 09:35 PM #1
Member
- Join Date
- Feb 2009
- Posts
- 18
- Rep Power
- 0
Sorting a deck of card objects by either suite or rank
My intentions are to implement 2 sorting functions that orders a deck of cards by suite and rank. My classes are shown below:
package com.base.net;
public class Card
{
private String rank; // face of card ("Ace", "Deuce", ...)
private String suit; // suit of card ("Hearts", "Diamonds", ...)
// two-argument constructor initializes card's face and suit
public Card( String cardRank, String cardSuite)
{
rank = cardRank; // initialize face of card
suit = cardSuite; // initialize suit of card
} // end two-argument Card constructor
//getter and setter methods
public String getRank()
{
return rank;
}
public void setRank(String rank)
{
this.rank = rank;
}
public String getSuit()
{
return suit;
}
public void setSuit(String suit)
{
this.suit = suit;
}
/*
public int compareTo(Card crd) {
if (crd instanceof Card) {
Card card = (Card) crd;
if (this.rank > card.getRank())
return 1;
else if (this.rank < card.getRank())
return -1;
}
return 0;
}
*/
// return String representation of Card
public String toString()
{
return rank + " of " + suit;
} // end method toString
} // end class Card
Any help would be greatly appreciated.package com.base.net;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
public class Deck
{
private final String [] suite = {"Clubs", "Diamonds", "Hearts", "Spades"};
private final String [] rank = {"Ace","2","3","4","5","6","7","8","9","10","Jack" ,"Queen","King"};
private static List<Object> deckofcards = new ArrayList<Object>();
public Deck()
{
for(int i=0; i<suite.length; i++)
{
for(int j=0; j<rank.length; j++)
{
deckofcards.add(new Card(rank[j],suite[i]));
}
}
}
public List getDeckofcards()
{
return deckofcards;
}
public int getSuiteSize()
{
return suite.length;
}
public int getRankSize()
{
return rank.length;
}
public int getDeckSize()
{
return deckofcards.size();
}
public void viewDeck()
{
try
{
Iterator iter = deckofcards.iterator();
while (iter.hasNext())
{
System.out.println(iter.next());
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void shuffle()
{
// This method converts a list of objects into an array.
// Manipulates the array (shuffling).
// Converts the array back to a list (S.A.T - Simple As That).
try
{
Object [] cards = deckofcards.toArray();
Random randomNumbers = new Random();
int currentCard = 0; // reinitialize currentCard
for ( int first = 0; first < cards.length; first++ )
{
int second = randomNumbers.nextInt( cards.length );
Object temp = cards[ first ];
cards[ first ] = cards[ second ];
cards[ second ] = temp;
}
deckofcards = Arrays.asList(cards);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void pickRandomCard()
{
try
{
Random randomNumbers = new Random();
int rand = randomNumbers.nextInt( deckofcards.size() );
System.out.println(deckofcards.get(rand).toString( ));
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void resetCards()
{
deckofcards = null;
}
protected void finalise()
{
deckofcards = null;
System.gc();
}
public void orderDeckofCards(Deck d)
{
}
public static void main(String args[])
{
Deck d = new Deck();
//d.shuffle();
d.viewDeck();
//d.pickRandomCard();
//d.orderDeckbySuite();
}
}
- 12-13-2010, 12:22 AM #2
Senior Member
- Join Date
- Mar 2010
- Posts
- 953
- Rep Power
- 4
1. Why are you doing List<Object>? Don't you want a simple List<Card>?
2. Create two new simple classes, RankComparator and SuitComparator, each of which implements Comparator<Card>. Each will need to implement the compare(Card card1, Card card2) method.
3. Sort your List by passing one of the two Comparator classes to the sort() method:
What the heck, I'll show you the whole trick. If this is for homework, you may not want to use enums (even though that's the right way to do it), as you may not have learned about them yet. Same goes for Collections.shuffle() and Collections.sort().Java Code:Collections.sort(deckofcards, new RankComparator());
Java Code:package org.javaforums.sample.deckofcards; public class Card { public enum Rank {ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING}; public enum Suit {CLUBS, DIAMONDS, HEARTS, SPADES}; private Rank rank; private Suit suit; public Card(Rank rank, Suit suit) { this.rank = rank; this.suit = suit; } /** * @return the rank */ public Rank getRank() { return rank; } /** * @return the suit */ public Suit getSuit() { return suit; } public String toString() { return rank + " of " + suit; } }-Gary-Java Code:package org.javaforums.sample.deckofcards; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class DeckOfCards { private List<Card> deck = new ArrayList<Card>(); private RankComparator rankComparator = new RankComparator(); private SuitComparator suitComparator = new SuitComparator(); public DeckOfCards() { for (Card.Suit suit : Card.Suit.values()) { for (Card.Rank rank : Card.Rank.values()) { deck.add(new Card(rank, suit)); } } } public void shuffle() { Collections.shuffle(deck); } public void sortByRank() { Collections.sort(deck, rankComparator); } public void sortBySuit() { Collections.sort(deck, suitComparator); } public String toString() { StringBuilder sb = new StringBuilder(); for (Card card : deck) { sb.append(card + "\n"); } return sb.toString(); } class RankComparator implements Comparator<Card> { @Override public int compare(Card card1, Card card2) { if (card1.getRank() == card2.getRank()) { return card1.getSuit().compareTo(card2.getSuit()); } return card1.getRank().compareTo(card2.getRank()); } } class SuitComparator implements Comparator<Card> { @Override public int compare(Card card1, Card card2) { if (card1.getSuit() == card2.getSuit()) { return card1.getRank().compareTo(card2.getRank()); } return card1.getSuit().compareTo(card2.getSuit()); } } public static void main(String[] args) { DeckOfCards myDeck = new DeckOfCards(); System.out.println("New deck..."); System.out.println(myDeck); myDeck.shuffle(); System.out.println("Shuffled..."); System.out.println(myDeck); myDeck.sortByRank(); System.out.println("Sorted by rank..."); System.out.println(myDeck); myDeck.sortBySuit(); System.out.println("Sorted by suit..."); System.out.println(myDeck); } }Last edited by gcalvin; 12-13-2010 at 12:32 AM. Reason: changed order of suits to match Bridge suits, and ranks to put ACE first
- 12-13-2010, 11:12 AM #3
Member
- Join Date
- Feb 2009
- Posts
- 18
- Rep Power
- 0
Hi Gary
Thank you for your kind input. It certainly breathes life into resolving this problem from another angle.
In response to your question, I had casting issues when I tried to use List<Card> so I used List<Object>.
I am familiar with enums but I dont use them often as I should do.
Similar Threads
-
Sorting objects with 2 strings arguments and 2 int arguments
By tirwit in forum New To JavaReplies: 8Last Post: 09-23-2010, 12:07 AM -
Question Card Layout, Card Management
By lrichil in forum AWT / SwingReplies: 1Last Post: 04-22-2010, 10:11 AM -
Sorting/Searching Objects with multiple types.
By gcampton in forum New To JavaReplies: 20Last Post: 10-21-2009, 11:58 PM -
Deck of Cards
By khunmato in forum New To JavaReplies: 13Last Post: 09-06-2009, 05:47 PM -
Problem with making/sorting a deck of cards
By Franneldort in forum New To JavaReplies: 9Last Post: 11-07-2008, 12:47 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks