JDK5 中的Printf()方法


JDK5中推出了Printf()方法,和C语言中的Printf()一样,以下的Sample是自己学习这个方法的一个小结,以下程序来源与网络,感谢该作者:
import java.util.Date;
import java.util.Locale;

/*
* printf各种格式测试
*/

public class MainClass {
 public static void main(String args[]) throws Exception {

   Date date = new Date();
   System.out.printf( Locale.CHINA, "The date is %tc/n", date );//打印时间,中文位置。
   System.out.printf("The DATE is %Tc/n", date );
   
   System.out.printf("%s://%s/%s/n", "http", "host", "path");//带参数的打印
   System.out.printf("boolean value is %1$b, %1$B/n", true );
   System.out.printf("hex value is %1$h, %1$H/n", new Date() );
   System.out.printf("hex value is %1$h, %1$H/n", 0xCAFE );//hex值
   System.out.printf("hex value is %1$x, %1$X/n", 0xCAFE );
   System.out.printf("hex value is %1$#x, %1$#X/n", 0xCAFE );

   System.out.printf( Locale.ITALIAN, "value: %f/n", 3.14 );//参数地方格式格式
   
   String [] words = new String [] { "a", "aaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" };
   System.out.printf( "%-10s %s/n", "Word", "Length" );
   for ( String word : words ){
     System.out.printf( "%-10.10s %s/n", word, word.length() );
   }
       
   System.out.printf("bool is %b/n", "a" );  //看是否String
   System.out.printf("char value is %c/n", 'a' );
     


 }
}  
1, Locale 对象表示了特定的地理、政治和文化地区。需要 Locale 来执行其任务的操作称为
  语言环境敏感的 操作,它使用 Locale 为用户量身定制信息。例如,显示一个数值就是语
  言环境敏感的操作,应该根据用户的国家、地区或文化的风俗/传统来格式化该数值。
2,  't', 'T'  日期/时间  日期和时间转换字符的前缀
    'c', 'C'  字符  结果是一个 Unicode 字符 
3, 参数索引
格式说明符可以通过三种方式引用参数:

显式索引 是在格式说明符中包含参数索引时使用。参数索引是一个十进制整数,用于指示参数在参数列表中的位置。第一个参数由 "1$" 引用,第二个参数由 "2$" 引用,依此类推。可以多次引用任何一个参数。
例如:

   formatter.format("%4$s %3$s %2$s %1$s %4$s %3$s %2$s %1$s",
                    "a", "b", "c", "d")
   // -> "d c b a d c b a"
 相对索引 是在格式说明符中包含 '<' ('/u003c') 标志时使用,该标志将导致重用以前格式说明符的参数。如果不存在以前的参数,则抛出 MissingFormatArgumentException。
    formatter.format("%s %s %<s %<s", "a", "b", "c", "d")
    // -> "a b b b"
    // "c" and "d" are ignored because they are not referenced
 普通索引 在格式说明符中既不包含参数索引也不包含 '<' 标志时使用。每个使用普通索引的格式说明符都分配了一个连续隐式索引,分配在独立于显式索引或相对索引使用的参数列表中。
   formatter.format("%s %s %s %s", "a", "b", "c", "d")
   // -> "a b c d"
 可能有一个使用所有索引形式的格式字符串,例如:

   formatter.format("%2$s %s %<s %s", "a", "b", "c", "d")
   // -> "b a a b"
   // "c" and "d" are ignored because they are not referenced

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值