1

I am working on a program with deck of cards. Currently I have:

public enum Numbers {
    N2, N3, N4, N5, N6, N7, N8, N9, N10, JACK, KING, QUEEN, ACE
}

I really need to display them as actual numbers like 1, 2, 3, 4 etc because I am trying to make my program more readable. I tried using a toString method like this but it doesn't really change anything:

N2 {

    public String toString() {
        return "2";
    }
}

Any guidance will be appreciated.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    `TWO`, `THREE`, `FOUR`, etc? – Phil May 11 '18 at 02:17
  • Agreed with @Phil. And if you want to manipulate actual integer, please consider [adding an attribute](https://stackoverflow.com/a/3054272/4906586) – Al-un May 11 '18 at 02:19
  • When you say actual numbers, do you want JACK, KING, QUEEN, ACE, to show up as 11, 12, 13, 1 ? – user1762507 May 11 '18 at 02:19
  • No, i would keep the JACK, KING, QUEEN and ACE either as they are or as J, K, Q, A –  May 11 '18 at 02:20
  • 1
    Something like [this](https://stackoverflow.com/questions/48758977/how-to-display-cards-in-a-card-game-in-java-and-have-them-clickable-for-selectio/48760120#48760120) (dig a little it's in there) or [this](https://stackoverflow.com/questions/32468982/java-printing-error-tostring-wont-print/32470422#32470422) – MadProgrammer May 11 '18 at 02:21
  • 1
    So return `name().startsWith("N") ? name().substring(1) : name().substring(0, 1)`. – shmosel May 11 '18 at 02:21

1 Answers1

3

You can pass whatever int value you want for each enum value in the constructor and at declaration time. And then use that in your toString() method. Like,

public enum Numbers {
    N2(2), N3(3), N4(4), N5(5), N6(6), N7(7), N8(8), N9(9), 
            N10(10), JACK(11), KING(12), QUEEN(13), ACE(1);
    Numbers(int value) {
        this.value = value;
    }

    private int value;

    public String toString() {
        return Integer.toString(value);
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • You could pass String to the constructor instead of converting the value each time. Maybe you don’t even need to pass value, simply set this.valueStr = Integer.toString(ordinal());. – Timir May 11 '18 at 03:47