Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking a new line using printf in java? Is %n correct?

I'm new to Java, and I am at my wits in end. I have got my program all to work, but just 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?

like image 1000
Beth Ann Meredith Avatar asked Nov 22 '12 10:11

Beth Ann Meredith


2 Answers

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).

like image 112
Mark Rotteveel Avatar answered Oct 24 '22 23:10

Mark Rotteveel


%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.

like image 33
Rohit Jain Avatar answered Oct 25 '22 00:10

Rohit Jain