Taking a new line using printf in java? Is %n correct?
Solution 1
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).
Solution 2
%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.
Beth Ann Meredith
Updated on July 05, 2022Comments
-
Beth Ann Meredith almost 2 years
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?