1. 程式人生 > >java佔位符

java佔位符

自己在這裡總結了三種佔位符形式:看下面程式碼即可

  1. String stringFormat  = "lexical error at position %s, encountered %s, expected %s ";   
  2. String messageFormat ="lexical error at position {0}, encountered {1}, expected {2}";  
  3. System.out.println(String.format(stringFormat, 123100456));  
  4. System.out.println(MessageFormat.format(messageFormat, new
     Date(), 100456));  

以上是兩種常見的使用形式,這裡還有另一種:

  1. %n$ms:代表輸出的是字串,n代表是第幾個引數,設定m的值可以在輸出之前放置空格   
  2. %n$md:代表輸出的是整數,n代表是第幾個引數,設定m的值可以在輸出之前放置空格,也可以設為0m,在輸出之前放置m個0
  3. %n$mf:代表輸出的是浮點數,n代表是第幾個引數,設定m的值可以控制小數位數,如m=2.2時,輸出格式為00.00

  1. 使用舉例:  
  2. String format = "%1$-25s%2$-48s";  
  3. System.out.format(format, "111","222");