简体   繁体   中英

print an array list in a list format in java w/o a loop

I am trying to re-define the method toString(), which has to return a String, to print an array list called cards with type Card. Because toString() has to return a string I can't use a loop to print out each element one by one, yet I want to print the array list in a list format. Basically, does anyone know how to make toString() return the array list cards as a string without using a loop?

cards array list definition

    ArrayList <Card> cards = new ArrayList<Card>();

Card class creator

    Card card1 = new Card(String suit, String rank, int value);

toString method

    public String deckToString(){
        return cards;
    }

What it should print

[suit, rank, value]
[suit, rank, value]
[suit, rank, value]
[suit, rank, value]
 etc.

What it currently prints

[suit, rank, value] [suit, rank, value] etc.

If I understand correctly, you want each value on its own line. In other words, join the values by a line break, instead of by comma.

public String deckToString() {
    return String.join("\n", cards.stream().map(Card::toString).collect(Collectors.toList()));
}
  public String deckToString(){
            temp="";
            for (int i = 0;i<cards.length;i++){
                  temp+=cards.get(i)+"\n";
            return temp;
  }

This simply iterates through the cards and adds a newline for each card and adds it to the return string. This is similar to janos solution but is more visually simple.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM