Search code examples
javagetter-setter

How to convert code from program to class (Getters and setter)


I'm trying to create a card game which would generate a random card from a different class. The problem is that the block of code dedicated for the random card is big. Is there a way to transfer this part of the code to my Card class and use getters and setters to use in the main program? Or is there a way to make the code for generating random card more simple?

Main program:

String NewCard = "";
int theSuit, theRank;

for(int i=0; i<1; i++) { 
theRank= (int)(Math.random()*13);
theSuit = (int)(Math.random()*5);

clsCard cardFace = new clsCard( theSuit, theRank);

NewCard =cardFace.toString();
System.out.println(" Your new card  is " + NewCard);

Card Class:

public class clsCard {

    private int value;
    private int rank, suit;
    private final int MaxFaceValue= 10;
    private static String[] suits = {"Joker","hearts","spades","diamond","clubs"};
    private static String[] ranks = {"Joker","Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};

    public clsCard(int suit, int rank)
    {
        this.rank=rank;
        this.suit=suit;
    }

    public @Override String toString()
    {
        if(ranks[rank].equals("Joker") || suits[suit].equals("Joker"))
            return "Joker";
        else
            return ranks[rank] + " of " + suits[suit];
    }

    public int getRank()
    {
        return rank;
    }

    public int getSuit()
    {
        return suit;
    }
}

Solution

  • Make a constructor that generates the random value

     public clsCard() {
        this.rank= (int)(Math.random()*ranks.length);
        this.suit= (int)(Math.random()*suits.length);
    }
    

    Make new clsCard() in the other class

    You can also make some public static List<clsCard> generateCards(int amount) method to not pollute your main method.

    Then you can do

    for (clsCard c : clsCard.generateCards(1)) {
        System.out.println(" Your new card  is " + c);
    }