何时在Java中使用printf语句?

时间:2013-12-10 03:26:21

标签: java formatting printf

什么时候将格式化字符串输出的代码视为好的代码:

int count = 5;
double amount = 45.6;
System.out.printf("The count is %d and the amount is %45.6", count, amount);

利用printf语句,通过以下代码:

int count = 5;
double amount = 45.6;
System.out.print("The count is " + count + "and the amount is " + amount);

使用print语句?

我已经阅读了JavaDocs,其中指出printf是“使用指定的格式字符串和参数将格式化字符串写入此输出流的便捷方法。”

但它没有说明按照惯例,我们应该使用一个而不是另一个?

那么,什么时候使用printf的编码很好,何时编码不好?

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

提供两种方法以方便编码器和不同的需要。如果您需要字符串格式化,那么请使用printf方法,但如果不需要格式化,只需使用print方法和void%d,%s等格式化程序。

如果你想控制精度&填充浮点数然后使用printf,否则去打印。

答案 1 :(得分:0)

为了方便起见,最近在java的历史中添加了printf,因为很多人都习惯了C风格的printf以及它可以做些什么。所以一个人并不比另一个人更好或更优先。当不需要特殊的printf格式时,常规的“打印”风格更清晰,更简单。