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?
我正在嘗試重新定義方法toString(),它必須返回一個字符串,以打印一個名為cardwithtype Card的數組列表。因為toString()必須返回一個字符串,我不能使用循環將每個元素逐個打印出來,但是我想要以列表格式打印數組列表。基本上,有誰知道如何讓toString()將數組列表卡作為字符串返回,而不使用循環嗎?
cards array list definition
卡數組列表定義
ArrayList cards = new ArrayList();
Card class creator
卡類創造者
Card card1 = new Card(String suit, String rank, int value);
toString method
toString方法
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.
2 个解决方案
#1
1
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()));
}
#2
0
public String deckToString(){
temp="";
for (int i = 0;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.
這只是簡單地遍歷卡片並為每張卡片添加一個換行符,並將其添加到返回字符串。這與janos的解決方案類似,但在視覺上更簡單。