Java

OOP GUIDE / WORK

 

CARD CLASS

 

Topics

  • Implementing the Comparable interface
  • Implementing the compareTo method (step by step)
  • Sorting object arrays with Comparable

 

 

TASK – PART 1 – TESTING THE FOLLOWING CARD CLASS

 

Consider the Card class below.  Create a Tester class with a main function.  Inside it, create a Card object and output it to screen to make sure you understand how it works.  Run your program a few times.

 

 

public class Card implements Comparable

{

     public String suit;  //hearts, diamonds, spades or clubs

     public int value;

    

     public Card()

     {

           value = (int)(Math.random() * 13 + 1);

          

           double rn = Math.random();

           if (rn <= 0.25)

                suit = "hearts";

           else if (rn <= 0.50)

                suit = "diamonds";

           else if (rn <= 0.75)

                suit = "spades";

           else

                suit = "clubs";

     }

    

     public String toString()

     {

           return value + " of " + suit;

     }

}

 

 

 

TASK – PART 2 – CARD ARRAY

 

a)    Inside your Tester class, remove anything you have in main.

 

b)    In main, create an array of Cards called hand.  Its size should be six.

 

c)     Remember that you need to loop over the array and construct each object one at a time.

d)    Again, loop over the array and output each Card element to screen.

e)    Notice that the cards are not in order.  Our next task will be to make it possible to sort the array. 

Note: At the moment, if you try to sort the array, you will get an array saying that Card cannot be casted to Comparable.  We need to go fix this.

 

 

TASK – PART 3 – IMPLEMENTING COMPARABLE

 

a)    Go back to your Card class and find the line public class Card and change it to

     public class Card implements Comparable

b)    Notice that the Card class now has an error.  That is because the Comparable interface requires us to implement the compareTo(Object obj) method. 

Add the method:

     public int compareTo(Object obj)
     {


     }


c)     For the first line of the method, we will cast obj into a Card object.  The line looks like this:

 

                    Card other = (Card)obj;

 

d)    We are now comparing the Card that we are inside (this) to the Card other. 

If
this.value is the same as other.value, then we should return 0.

If
this.value is less than other.value, we should return -1.

If
this.value is larger than other.value, we should return 1.

Note: Instead of
this.value, we can actually simply put value.

 

 

TASK – PART 4 – SORTING THE ARRAY

 

Since the Card class implements Comparable, you can simply use Arrays.sort(hand) to sort the Card array.  Try it.

Then output the array out to screen again.

Run the program to confirm that the array is now sorted.