Java

OOP GUIDE / WORK

 

CARD CLASS 2 SOLUTIONS

 

 

TASK – PART 1 – SETUP

 

  • No solution required

 

TASK – PART 2 – ALTERING COMPARETO

 

Here is my solution:

 

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;

     }

 

     @Override

     public int compareTo(Object o)

     {

           //We will compare this and o

           Card other = (Card)o;

 

           //If suits are the same

           if (this.suit.equals(other.suit))

           {

                if (this.value < other.value)

                {

                      return -1;

                }

                else if (this.value == other.value)

                {

                      return 0;

                }

                else

                {

                      return 1;

                }

           }

          

           //If suits are different

           //Order of suits: clubs, diamonds, spades and then hearts.

           if (this.suit.equals("clubs"))

           {

                return -1;

           }

           else if (this.suit.equals("diamonds") && !other.suit.equals("clubs"))

           {

                return -1;

           }

           else if (this.suit.equals("spades") && other.suit.equals("hearts"))

           {

                return -1;

           }

           else

           {

                return 1;

           }

     }

}



 

TASK – PART3 – TESTING

 

Below is my solution.  Note that the only that was changed here is the array’s size.

 

import java.util.Arrays;

 

public class Tester

{

     public static void main(String[] args)

     {

           Card[] hand = new Card[10];

 

           //Creating cards

           for (int i=0; i<hand.length; i++)

           {

                hand[i] = new Card();

           }

 

           //Output cards

           for (int i=0; i<hand.length; i++)

           {

                System.out.println(hand[i]);

           }

 

           Arrays.sort(hand);

           System.out.println("======");

          

 

           //Output cards

           for (int i=0; i<hand.length; i++)

           {

                System.out.println(hand[i]);

           }

     }

}