0

Question: How do I make my string look like this, instead of this with (String Builder)

What is Should Look Like:

"Assassin's Creed IV: Black Flag", released on: Nov 29, 2013

"Child of Light", released on: May 01, 2014

"Dragon Age: Inquisition", released on: Dec 18, 2014

I know some form of StringBuilder should be used however I have no idea how to format it. As my games are printing as:

What mine looks like:

["Assassin's Creed IV: Black Flag", released on: Nov 29, 2013 "Child of Light", released on: May 01, 2014 "Dragon Age: Inquisition", released on: Dec 18, 2014]

Below is my code snip-it where the dates are all appearing fine just they are not split over multiple lines

@Override
public String toString() {  
    DateFormat date = new SimpleDateFormat("MMM dd, yyyy");   
       return("\"" + game + "\"" + ", " + "released on: " + date.format(released.getTime()));
 }
  • Are you calling toString on each element in a list? it looks like your toString() is correct, you just need to add a newline character after each call to toString – Gene Taylor May 06 '16 at 05:22
  • As it prints out in a linked-list, if I add a new line (/n) at the end it just spaces out in the end as they are all concatinated together – PeterP1989 May 06 '16 at 05:23
  • One way to fix this is to iterate over the list calling System.out.println on each item ie myList.forEach(System.out::println) – Gene Taylor May 06 '16 at 05:26

2 Answers2

0

The problem is that you are calling toString on a collection that is not adding a newline between the toString of each element.

One solution is to instead iterate over the collection and call System.out.println on each item.

Another solution is to covert the List to a stream and then use the streams API to map each item to its toString and then collect together using "\n" as the seperator eg

myList.stream().map(g -> g.toString()).collect(Collectors.joining("\n"))
Gene Taylor
  • 541
  • 2
  • 10
0

Since you did not tell me what class is the toString method declared in, I'll call it ClassA.

You said in the comments that you are using a linked list to store ClassA objects. So I'll show you how to print each item in a linked list:

StringBuilder builder = new StringBuilder(); // StringBuilder is used to concatenate all the items in the list
for (ClassA item : theLinkedList) {
    builder.append(item.toString());
    builder.append("\n"); // Here I add the new line
}
System.out.println(builder);

If you are using Java8, you can use stream and `map to do this as well, as suggested in Gene Taylor's answer. It's much more elegant.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • My bad I can see I didn't add the class name it was called gamingList, how does that work with the date though, – PeterP1989 May 06 '16 at 05:42