Results 1 to 3 of 3
  1. #1
    coyne20 is offline Member
    Join Date
    Feb 2009
    Posts
    20
    Rep Power
    0

    Default 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
    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();
    }
    }
    Any help would be greatly appreciated.

  2. #2
    gcalvin is offline Senior Member
    Join Date
    Mar 2010
    Posts
    953
    Rep Power
    5

    Default

    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:
    Java Code:
            Collections.sort(deckofcards, new RankComparator());
    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:
    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;
    	}
    	
    }
    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);
    	}
    }
    -Gary-
    Last edited by gcalvin; 12-13-2010 at 01:32 AM. Reason: changed order of suits to match Bridge suits, and ranks to put ACE first

  3. #3
    coyne20 is offline Member
    Join Date
    Feb 2009
    Posts
    20
    Rep Power
    0

    Default

    Quote Originally Posted by gcalvin View Post
    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:
    Java Code:
            Collections.sort(deckofcards, new RankComparator());
    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:
    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;
    	}
    	
    }
    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);
    	}
    }
    -Gary-
    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

  1. Replies: 8
    Last Post: 09-23-2010, 01:07 AM
  2. Question Card Layout, Card Management
    By lrichil in forum AWT / Swing
    Replies: 1
    Last Post: 04-22-2010, 11:11 AM
  3. Sorting/Searching Objects with multiple types.
    By gcampton in forum New To Java
    Replies: 20
    Last Post: 10-22-2009, 12:58 AM
  4. Deck of Cards
    By khunmato in forum New To Java
    Replies: 13
    Last Post: 09-06-2009, 06:47 PM
  5. Problem with making/sorting a deck of cards
    By Franneldort in forum New To Java
    Replies: 9
    Last Post: 11-07-2008, 01:47 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •