Skip to content

Need help to run an if statement inside an object to change that objects attributes (JAVA)

Im not extremely high level at this and this is my first time really working with objects and classes. I am trying to make a card game and want to color the card’s suit name either red or black with the Java color code things. Each card is its own object, with a suit and a number value. Heres the “Card” class:

        public class Card {
String suit = Main.generateCardSuit();
int value = Main.generateCardValue();

**if(suit.equals("Spades") || suit.equals("Clubs")){
    String cardColor = Colors.WHITE;
} else {
    String cardColor = Colors.RED;

String cardDisplay = value + ", "+ cardColor + suit + Colors.RESET;}

the methods in the Main class that determine the suit and values:

` public static String generateCardSuit() {
        String cardSuit = "0";
        int suitDeterminer = (int) Math.ceil(Math.random() * 4);
        switch (suitDeterminer) {
            case 1:
                cardSuit = "Spades";
            case 2:
                cardSuit = "Clubs";
            case 3:
                cardSuit = "Hearts";
            case 4:
                cardSuit = "Diamonds";
        return cardSuit;

    public static int generateCardValue() {
        int gameValue = (int) Math.ceil(Math.random() * 13+1);
        return gameValue;

How the Card class is used:

   public static void printUserHand(ArrayList < Card > userHand) {
    for (int i = 0; i < userHand.size(); i++) {
        System.out.println(i + ": " + userHand.get(i).cardDisplay);

public static void main(String[] args) {
    ArrayList < Card > userHand = new ArrayList < Card > ();
    for (int i = 0; i < 7; i++) {
        userHand.add(new Card());
    for (int i = 7; i > 0; i--) {
        Card gameCard = new Card();
        System.out.println("The dealer turns up a: " + gameCard.cardDisplay + "n");

So i need each cards color to be an attribute, but the bolded IF statement I have in the object doesnt work. Based on how my code is working, I dont know of a way that it could go in the Main class without causing a lot of other problems.


Your Card class has a severe problem: it is not a class at all, it tries to execute code outside a method.

Give it a private field called cardDisplay and initialize it in a constructor of Card. Add a method to retrieve the value of cardDisplay:

private final String cardDisplay;

public Card() {
  // put all the code from your version of Card here
  this.cardDisplay = cardDisplay;

public String getCardDisplay() {
  return cardDisplay;

If you skip the declaration in your code (that’s where you specify the type of the local variable), you can even save a line with

  cardDisplay = value + ", "+ cardColor + suit + Colors.RESET;

Just don’t skip the declaration for real local variables that are not available as fields, like probably cardColor.