Search code examples
javajoptionpanestring-concatenationsystem.out

system.out of object to string


Very new to Java so all help is appreciated, but please give the more direct answer possible.

I am trying to change a System.out.println statement to one that will be displayed in a JOptionPane. This is my first attempt at GUI, and find myself hopelessly lost.

I have Strings being printed through several methods in order to display one snippet of output. The part of the output I want to go in one pane, so I think the easiest way might be to concatenate a string.

I have an ArrayList hard that holds a Card value. I overloaded the toString method in Card for the ranks, and the Suit enum that the Card uses returns Strings ("Heart", Spade", etc.)

for(int x = 0; x < hand.size(); x++){
    System.out.println(hand.get(x));
} //correctly prints the code

I was trying to do String handString = "";

    for(int x = 0; x < hand.size(); x++){
        handString = handString.concat(hand.get(x)); //also tried concat(toString(hand.get(x))
    }

Can anyone tell me why I am not able to change the Card toString and why it prints to the console, but why I can't put it to a string? I have a feeling this is very obvious but nothing I can find online seems to help with my combination of enums and class objects.

Also, how would I go about turning several printings to the console to one printing in a JOptionPane?


Solution

  • Can you try:

    for(int x = 0; x < hand.size(); x++){
       handString += hand.get(x);
       handString += "\n"; 
    }
    

    The plus(+) operator takes care of conversion to String (using the toString() method for objects - which you have overriden).

    You can also use the foreach loop here (much shorter, personal preference though):

    for (Card card : hand) {
        handString += card;
        handString += "\n";
    }