?
Solved

how to put cards in order by using Comparable?

Posted on 2004-08-06
14
Medium Priority
?
267 Views
Last Modified: 2010-03-31
Hello
can anybody help on how to code  my Card.java class that implements Comparable?

my code prints out fours hands with 13 random card but they r unordered, how can I ordered them by using Comparable in Card.java class ?

any help please

public class Card{

  private int value, suit;

  public Card(int val, int s){
    value = val;
    suit = s;
  }
  public int getValue(){
    return value;
  }

  public int getSuit(){
    return suit;
  }

  public void setValue(int v){
    value = v;
  }

  public void setSuit(int s){
    suit = s;
  }
 
  public String toString() {
      return "Suit = " + suit + " Value = " + value;
  }
}


/*
 * CardGame.java
 *
*/

import java.util.*;



public class CardGame {
    List theDeck = new ArrayList(52);
    Random r = new Random();
     
    public CardGame() {
        // Fill the deck
        for (int j = 1; j <= 4; j++)
            for (int i = 1;i <= 13;i++)
               theDeck.add( new Card(i,j) );
    }

    public List deal(int number) {
        List hand = new ArrayList();
        while (hand.size()<number) {
            int index = r.nextInt( theDeck.size() );
            hand.add( theDeck.get(index) );
            theDeck.remove(index);
        }
        return hand;
    }
   
    public void listHand(List hand) {
        for (int i=0; i<hand.size(); i++)
            System.out.println( ((Card) hand.get(i)) );
    }

    public static void main(String args[]) {

         CardGame cg = new CardGame();
         List hand1 = cg.deal(13);
         System.out.println("Hand 1 contains:");
         cg.listHand(hand1);
         List hand2 = cg.deal(13);
         System.out.println("Hand 2 contains:");
         cg.listHand(hand2);
         List hand3 = cg.deal(13);
         System.out.println("Hand 3 contains:");
         cg.listHand(hand3);
         List hand4 = cg.deal(13);
         System.out.println("Hand 4 contains:");
         cg.listHand(hand4);
    }
}
0
Comment
Question by:anosTekbot
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 3
  • 2
  • +2
14 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 11738992
I'm not totally sure about the ordering rules for cards, but i think this is right:

public int compareTo(Object other) {
      Card otherCard = (Card)other;
      int returnValue = value - otherCard.getValue();
      if (returnValue == 0) {
            return suit - other.getSuit();
      }
      else {
            return returnValue;
      }
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11739001
That of course should be made a method of Card and

>>public class Card{

should be

public class Card implements Comparable {
0
 

Author Comment

by:anosTekbot
ID: 11739093
the order rule is like that for suit ( Clubs, Diamonds Hearts Spades)
for values ( highest to lowest) --> ( ace king queen .....  2 )
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 86

Expert Comment

by:CEHJ
ID: 11739516
Yes, i know, but what i meant is which takes priority - the suit or the rank? (My code assumes rank then suit)
0
 

Author Comment

by:anosTekbot
ID: 11739557
I wrote this code for compareTo method
but how I can order suits (Clubs, Diamonds Hearts Spades) and values ( highest to lowest) in my cardgame class?

so i want to get an output such as :
player1: Clubs 14 7 3 2

public class Card implements Comparable {
  private int suit;  // Clubs, Diamonds, Hearts, Spades.
  private int val;   // Card number: 2-14.
 
  public int compareTo (Object rhs) {
    Card card = (Card)rhs;
    if (this.suit < card.suit) return –1;
    if (this.suit > card.suit) return  1;
    if (this.val  < card.val ) return –1;
    if (this.val  > card.val ) return  1;
    return 0;
  }
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11739595
Your code would rank the 2 of spades above the king of clubs, which is not right AFAIK
0
 

Author Comment

by:anosTekbot
ID: 11739624
any suggestion?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11739643
Yes - change it to mine ;-)
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11739653
You must also use the accessor method of the other class:

>>if (this.val  < card.val ) return –1;

should be

if (this.val  < card.getValue() ) return –1;
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11739833
In my code,

>>return suit - other.getSuit();

should be

return suit - otherCard.getSuit();
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11740143
Just a remark. I read

>> private int val;   // Card number: 2-14.

But your card values are 1 - 13 :

public CardGame() {
        // Fill the deck
        for (int j = 1; j <= 4; j++)
            for (int i = 1;i <= 13;i++)    // <<<<<<<<<<<<<< I changed that in antoher Q since that's more like real life, isn't it?
               theDeck.add( new Card(i,j) );
}


0
 
LVL 92

Accepted Solution

by:
objects earned 2000 total points
ID: 11740504
try this:

public class Card impleemnts Comparable {

  private int value, suit;

  public Card(int val, int s){
    value = val;
    suit = s;
  }
  public int getValue(){
    return value;
  }

  public int getSuit(){
    return suit;
  }

  public void setValue(int v){
    value = v;
  }

  public void setSuit(int s){
    suit = s;
  }

  public int compareTo (Object rhs) {
    Card card = (Card)rhs;
    return (value==card.value ? suit - card.suit : value - card.value);
  }

  public String toString() {
      return "Suit = " + suit + " Value = " + value;
  }
}
0
 
LVL 92

Expert Comment

by:objects
ID: 11741105
Also instead of using Random to select a Card from deck, you could just shuffle the deck initially making your code simpler:

    public CardGame() {
        // Fill the deck
        for (int j = 1; j <= 4; j++)
            for (int i = 1;i <= 13;i++)
               theDeck.add( new Card(i,j) );
        Collections.shuffle(theDeck);
    }

    public List deal(int number) {
        List hand = new ArrayList();
        while (hand.size()<number) {
            hand.add( theDeck.remove(0) );
        }
        return hand;
    }
0
 
LVL 1

Expert Comment

by:wolfc
ID: 11742529
I like objects implementation of CEHJ's idea.
0

Featured Post

Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month14 days, 17 hours left to enroll

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question