简体   繁体   English

Java输出格式

[英]Java output formatting

I was wondering if Java has some sort of class to help on output formatting. 我想知道Java是否有某种类来帮助输出格式化。 I know in C++, in iomanip, there is a method call setw. 我知道在C ++中,在iomanip中,有一个方法调用setw。 I was wondering if Java has something similar to this. 我想知道Java是否有类似的东西。

Have a look at java.util.Formatter . 看看java.util.Formatter

String.format() provides a convenient wrapper. String.format()提供了一个方便的包装器。

For example (modified from an example on the link): 例如(从链接上的示例修改):

   String s = String.format("e = %+10.4f", Math.E);

It goes beyond C's ?printf formats. 它超越了C的?printf格式。 For example, it supports an optional locale, and format symbols can be associated with an argument by explicit index rather than implicit. 例如,它支持可选的语言环境,格式符号可以通过显式索引而不是隐式与参数关联。

Edit: Fixed the link above. 编辑:修正了上面的链接。

String.format(..)和可能的java.text.*

有Formatter类及其变体:String.format,PrintStream.printf。

The simplest approach is to use printf() which works much the same as printf() in C. 最简单的方法是使用printf(),它与C中的printf()非常相似。

double pi = Math.PI;
System.out.printf ("pi = %5.3f%n", pi);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM