12

我是 Java 新手,最后我还是很机智。我的程序已经全部运行,但在打印输出时只需要格式化方面的帮助。

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

我的输出是

Stacey Francis   is compatible with     Owen Farrell   Jack Clifford  Joshua Watkins 

我希望我的输出是(不重复 stacey francis 的名字或“兼容”:

Stacey Francis   is compatible with  Owen Farrell
                                 
                          Jack Clifford
                                 
                          Joshua Watkins

只是想知道如何解决这个问题?

4

3 回答 3

16

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

于 2012-11-22T10:38:30.917 回答
9

%n应该工作。但问题是,您刚刚在格式字符串的末尾使用了它。您需要将其插入适当的位置:-

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

您还可以"\n"在格式说明符之间使用来打印换行符:-

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

此外,我已将length最后两个名称从15to增加45,以将它们格式化在前面的名称下方。

于 2012-11-22T10:33:50.517 回答
0

can you 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");
于 2012-11-22T10:38:32.433 回答