Chinaunix首页 | 论坛 | 博客
  • 博客访问: 805806
  • 博文数量: 780
  • 博客积分: 7000
  • 博客等级: 少将
  • 技术积分: 5010
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-12 09:11
文章分类

全部博文(780)

文章存档

2011年(1)

2008年(779)

我的朋友
最近访客

分类:

2008-09-12 09:11:58

DK5.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的实例. PrintStream, java.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);

         }

       }

[1]     

【责编:Ken】

--------------------next---------------------

阅读(288) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~