java佔位符
阿新 • • 發佈:2019-02-20
自己在這裡總結了三種佔位符形式:看下面程式碼即可
- String stringFormat = "lexical error at position %s, encountered %s, expected %s ";
- String messageFormat ="lexical error at position {0}, encountered {1}, expected {2}";
- System.out.println(String.format(stringFormat, 123, 100, 456));
- System.out.println(MessageFormat.format(messageFormat, new
以上是兩種常見的使用形式,這裡還有另一種:
- %n$ms:代表輸出的是字串,n代表是第幾個引數,設定m的值可以在輸出之前放置空格
- %n$md:代表輸出的是整數,n代表是第幾個引數,設定m的值可以在輸出之前放置空格,也可以設為0m,在輸出之前放置m個0
- %n$mf:代表輸出的是浮點數,n代表是第幾個引數,設定m的值可以控制小數位數,如m=2.2時,輸出格式為00.00
- 使用舉例:
- String format = "%1$-25s%2$-48s";
- System.out.format(format, "111","222");