Search code examples
javaarraysstringobjectblackjack

Objects from Array to String


So I am simulating a game of Blackjack and in my class Deck, one of my methods is

public String toString(){
}

Its purpose is to return a string with 52 lines and each line should have a description of the card in the deck from top to bottom. I have already created the array which contains 52 objects for the cards, that is {1 of Hearts, 2 of Hearts,…} But i am not sure how to start this part. Can someone help me this part, please?

I was thinking if I could create the following:

public String toString(){
String myCards= myCards+card // supposed to add the string card to its already existing string
String card;
    for(int i=0; i<52; i++){

And then to here access the object at each index and convert that to the string card. Then each time the loop goes, a new string would be added to the string my Cards, until getting all the cards. But, i am not really sure how to do that. Can anyone help me start this, pls?

THANK YOU VERY MUCH!!! I GOT IT TO WORK. I MODIFIED SOME STUFF AND IT WORKED.THANKS AGAIN!!!


Solution

  • You would likely want to give your Card class a toString method that returns the card's details and for your Deck class, use a for loop something like this:

    string outStr="";
    static String newline = System.getProperty("line.separator");
    for (int i=1; i<cardArray.size(); i++){
        outStr+=newline+cardArray[i].toString();
    }
    return outStr;
    

    I might not have gotten the Java syntax quite right, but that should be a good start.