`

System.out.format的使用

    博客分类:
  • Java
阅读更多

JDK5.0允许象C语言那样直接用printf()方法来格式化输出,并且提供了许多参数来格式化输入,调用也很简单:

System.out.format("Pi is approximately  %f", Math.Pi);

   System.out.printf("Pi is approximately  %f", Math.Pi);

 printf()和 format() 方法具有相同的功能. System.out 是 java.io.PrintStream的实例PrintStreamjava.io.PrintWriter, 和 java.lang.String 每个类都有四个新的格式化方法:

format( String format, Object... args);

printf( String format, Object... args);

format( Locale locale, String format, Object... args);

printf( Locale locale, String format, Object... args);

 

同时,以前的formatter类也提供了更完善的方法来格式化,例如:

formatter.format("Pi is approximately %1$f," +

        "and e is about %2$f", Math.PI, Math.E);

 

格式化元素的构成如下:

%[argument_index$][flags][width][.precision]conversion

其中:

argument_index是一个正整数,说明了参数的位置,1为取第一个参数

width表示输出的最小字母个数

precision代表数字的小数位数

conversion代表被格式化的参数的类型:

f  float,

t  time

d  decimal

o octal

x  hexadecimal

s  general

c  a Unicode character

以下是个例子:

package format;

 

   import java.util.Formatter;

 

   public class UsingFormatter {

 

     public static void main(String[] args) {

       if (args.length != 1) {

         System.err.println("usage: " +

           "java format/UsingFormatter ");

         System.exit(0);

       }

       String format = args[0];

 

       StringBuilder stringBuilder = new StringBuilder();

       Formatter formatter = new Formatter(stringBuilder);

       formatter.format("Pi is approximately " + format +

         ", and e is about " + format, Math.PI, Math.E);

       System.out.println(stringBuilder);

     }

   }

 

//控制台调用

java format/UsingFormatter %f

//输出

Pi is approximately 3.141593, and e is about 2.718282

//控制台调用

java format/UsingFormatter %.2f

//输出

Pi is approximately 3.14, and e is about 2.72

//控制台调用

java format/UsingFormatter %6.2f

//输出(有空格来填补长度)

Pi is approximately   3.14, and e is about   2.72

//控制台调用

java format/UsingFormatter  %1$.2f

//输出

Pi is approximately 3.14, and e is about 3.14

 

//改变区域设置

package format;

 

   import java.util.Formatter;

   import java.util.Locale;

 

   public class UsingFormatter {

 

     public static void main(String[] args) {

       if (args.length != 1) {

         System.err.println("usage: " +

           "java format/UsingFormatter <format string>");

         System.exit(0);

       }

       String format = args[0];

 

       StringBuilder stringBuilder = new StringBuilder();

       Formatter formatter = new Formatter(stringBuilder,

                                   Locale.FRANCE);

       formatter.format("Pi is approximately " + format +

         ", and e is about " + format, Math.PI, Math.E);

       System.out.println(stringBuilder);

     }

   }

//控制台调用

java format/UsingFormatter %.2f

//输出

Pi is approximately 3,14, and e is about 2,72

 

//采用format,printf的可替代写法

package format;

 

   public class UsingSystemOut {

 

     public static void main(String[] args) {

       if (args.length != 1) {

         System.err.println("usage: " +

           "java format/UsingSystemOut <format string>");

         System.exit(0);

       }

       String format = args[0];

 

       System.out.format("Pi is approximately " + format +

         ", and e is approximately " + format, Math.PI, Math.E);

     }

   }

//控制台调用

java format/UsingSystemOut %.2f%n

//输出

Pi is approximately 3.14

   , and e is about 2.72

 

对时间的格式化用字母t来代表,通常在t后面加上特殊的字符来显示时间的某个部分:

tr  hour and minute,

tA  the day of the week

tB  the name of the month

te  the number of the day of the month

tY  the year

//eg.

package format;

 

   import java.util.Calendar;

 

   public class FormattingDates  {

 

     public static void main(String[] args) {

       System.out.printf("Right now it is %tr on " +

                         "%<tA, %<tB %<te, %<tY.%n",

                         Calendar.getInstance());

     }

   }

//说明:“<”指示采用的参数为前一个被格式化的参数

//输出

Right now it is 01:55:19 PM on Wednesday, September 22, 2004.

分享到:
评论

相关推荐

    Tomcat使用Log4j输出catalina.out日志

    通过以上步骤,Tomcat服务器将使用Log4j来管理catalina.out日志,这不但解决了日志文件过大和格式不统一的问题,而且提供了更丰富的日志管理功能,例如,可以利用Log4j强大的过滤、路由和格式化等功能,将日志管理得...

    JAVA_String.format

    System.out.println(String.format("%1$,09d", -3123)); // 输出:-0003,123 System.out.println(String.format("%1$#9x", 5689)); // 输出:0x1639 ``` ### 浮点数格式化 浮点数格式化在上述基础上增加了`[精度]`...

    基于c#的图像处理源代码

    curBitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Tiff); break; case "png": curBitmap.Save(fileName, System.Drawing.Imaging.ImageFormat.Png); break; default: break; } } } private...

    java实验报告 行列对齐的九九表

    一个更为通用的方法是使用格式化字符串来确保每个乘积的宽度一致,例如使用`String.format()`方法。 下面是一个使用格式化字符串实现的行列对齐的九九表示例: ```java public class AlignedMultiplicationTable {...

    Java字符串_日期_数字格式化输出

    System.out.println(nf.format(88888.88)); // 输出 "¥88,888.88" ``` 2. **DecimalFormat 类**:更高级的数字格式化工具,可以自定义各种格式模式。 - **示例代码**: ```java DecimalFormat df = new ...

    java String format方法使用

    要输出一个百分比符号,可以使用转义字符“%”,例如,System.out.println(String.format("%1$d%%", 12)); 将输出“12%”。 平台独立的行分隔符 可以使用 String.format("%n") 来取得平台独立的行分隔符。 日期...

    EmvReader Java Code

    System.out.println("#ERROR# Invalid reader index format '"+args[0]+"'" ); System.exit(3);// throw new Exception( "Invalid reader index '"+args[0]+"'" ); } if ( iReader &gt;= terminals.size() ) {...

    string.format实例

    在Java中,你可以使用`System.getProperty()`方法来获取系统属性,其中包括程序运行路径。例如: ```java String currentPath = System.getProperty("user.dir"); System.out.println("当前程序运行路径: " + ...

    kuhuesocket

    System.out.println("***************欢迎使用青鸟超市管理系统***************"); do{ System.out.println("1 .登陆 \n2 .退出系统"); System.out.println("******************请选择数字1/2*************...

    System.currentTimeMillis()计算方式与时间的单位转换详解

    - 在处理时间时,如果你只需要毫秒级别的精度,直接使用 `System.currentTimeMillis()` 就足够了,它避免了创建不必要的 `Date` 对象,从而提高了程序性能。 - 如果需要将毫秒转换成其他时间单位,可以通过除法...

    java字符串格式化String.format()

    System.out.println(String.format("%1$,09d", -3123)); // 输出: -0003,123 System.out.println(String.format("%1$9d", -31)); // 输出: -31 System.out.println(String.format("%1$-9d", -31)); // 输出: -31 ...

    java获得各种时间

    System.out.println("获取当前日期:" + tt.getNowTime("yyyy-MM-dd")); ``` 这里使用`SimpleDateFormat`类来格式化当前日期。`"yyyy-MM-dd"`是一个日期格式字符串,表示年月日。通过`new Date()`获取当前系统时间...

    4种方法在java中,对日期时间的比较.docx

    import java.time.format.DateTimeFormatter; @Test void testDateCompareJava8() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate date1 = LocalDate.parse("2009-12-31...

    安卓反编译dex文件格式实例分析

    本例中提及了 Android Open Source Project 中的 Dalvik Executable Format 文档,该文档详细描述了 dex 文件的格式和各个字段的具体含义,是深入理解 dex 文件必不可少的资料来源。通过对 dex 文件格式的深入分析,...

    33Java大整数高精度1

    在 Java 中,我们可以使用 `System.out.printf()` 来输出格式化字符串,例如: ```java import java.util.*; import java.text.*; public class Main { public static void main(String[] args) { DecimalFormat...

    java使用DateFormat类转换时间格式.docx

    System.out.println("******************************************"); // 使用默认样式(通常是MEDIUM)格式化日期 s = DateFormat.getDateInstance().format(d); System.out.println(s); // 输出:2005-4-16 ...

    java运算java运算.doc

    System.out.println(0.05 + 0.01); System.out.println(1.0 - 0.42); System.out.println(4.015 * 100); System.out.println(123.3 / 100); ``` 输出结果可能不是我们预期的结果: ``` 0.060000000000000005 0....

    操作系统Java实现SJF代码

    public class SJF { public static void main(String[] args) { Scanner in= new Scanner(System.in);... System.out.println("平均周转时间为:"+df.format(AverageWT)); System.out.println

    java字符格式化

    System.out.printf("上面价格的指数和浮点数结果的长度较短的是:%g%n", 50 * 0.85); System.out.printf("上面的折扣是%d%%%n", 85); System.out.printf("字母 A 的散列码是:%h%n", 'A'); } ``` 运行这段代码,...

Global site tag (gtag.js) - Google Analytics