How do you write an toString() method for an int array? Say to return the string representation of a 52 card pack?
Here is an example array as part of a class:
{ int[] cards = new int[52]; public void Deck() { // Setting up array String[] suits = {"SPADES", "CLUBS", "HEARTS", "DIAMONDS"}; String[] ranks = {"TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "JACK", "QUEEN", "KING", "ACE"}; { // Initalising array for (int i = 0; i < cards.length; i++) { cards[i] = i; } } }
This is being done in an object oriented manner. How would a toString() method be written in this case in order to return a string representation of the pack of cards or in this case, the array?
I have currently used:
@Overide public String toString() { return getClass().getName() + "[cards[]= " + cards[] + "]"; }
I have also used a similar toString() method written as:
return getClass().getName() + "[suits[]= " + suits[] + "ranks[]= " + ranks[] + "]";
It’s the same kind of toString() method I have used for other values and it normally works. Though now I get this error for both (or at least, the first one):
cannot find symbol symbol: Class cards //which I dont have other than the array at the top location: Class Pack // The class the array is currently in unexpected type required: value found: class '.class.' expected
As for printing it, I want it either formatted as a list, or a grid.
Advertisement
Answer
If you want to do it more OOPish, you should create a new class Card
.
The Card
class will have to fields suit
, and rank
(the type could be an enum here).
Make sure Card
overwrites toString()
, and make sure your array in Deck
is Card[]
(and NOT int[]
).
Now you can easily implement toString()
by invoking Arrays.toString()
, which will in its turn invoke the toString()
of each Card
object, resulting in the required representation of your deck.
As for your code (which was added later):
return getClass().getName() + "[cards[]= " + cards[] + "]";
Will not compile because cards[]
is not a value – cards
is, but it will not get you what you want. Array’s toString()
does NOT produce the content of the array, and you should use Arrays.toString(cards)
.
However, I suggest redesigning the code as described at the head of this answer.