16

I'm new to Java and I'm at my wits' end.

I have got my program to work, but I need help with the formatting when printing out.

if(count == 3)
    System.out.printf ("%-15s %15s %15s %15s %15s %n", n, " is compatible with ",dates[k],dates[k+1],dates[k+2]);

My output is:

Stacey Francis   is compatible with     Owen Farrell   Jack Clifford  Joshua Watkins 

I would like my output to be (without repeating stacey francis name or "is compatible with":

Stacey Francis   is compatible with  Owen Farrell
                                 
                          Jack Clifford
                                 
                          Joshua Watkins

Just wondering how to go about this?

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Beth Ann Meredith
  • 181
  • 1
  • 4
  • 10

3 Answers3

23

Yes, %n is a newline in printf. See the documentation of java.util.Formatter, specifically the conversion table which specifies:

'n' line separator The result is the platform-specific line separator

Your output currently only has a linebreak at the end, not at the points that you seem to want them. You would need to use a format like:

"%-15s %15s %15s %n %15s %n %15s %n"

(and maybe some tabs thrown in there for alignment).

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
11

%n should have worked. But the problem is, you have just used it at the end in your format string. You need to insert it at appropriate places: -

"%-15s %15s %15s %n %45s %n %45s"

You can also use "\n" between your format specifiers to print a newline: -

System.out.printf ("%-15s %15s %15s \n %45s \n %45s", 
                     n, " is compatible with ", dates[k],dates[k+1],dates[k+2]);

Also, I have increased the length of last two names from 15 to 45, to format them just below the previous names.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

You can try this:

if (count == 3) {
    System.out.printf("%-15s %15s %15s %15s %15s %n", n, " is compatible with",
            dates[k],dates[k+1],dates[k+2]+"\n");
}
Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Srinivas B
  • 1,821
  • 4
  • 17
  • 35