package tigers;
import Java.util.Formatter;
public class FormatPrint2 {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
Formatter forma = new Formatter(sb);
forma.format("%12.10f", Math.PI);
System.out.println(forma);
System.out.printf("%12.10f", Math.PI);
}
}
結果:
C:\tiger>javac -d c:\tiger\cls c:\tiger\src\FormatPrint2.Java
C:\tiger>Java -classpath c:\tiger\cls tigers.FormatPrint2
3.1415926536
3.1415926536
三、可變長度參數與格式化輸出
package tigers;
public class FormatPrint {
public static void main(String[] args) {
printf("%, %, % and % are my frIEnds!", "BITAN", "HELEN", "KATHY", "SUSAN");
printf("%, %, %, % and % are my favorites" ,"A", "B", "C", "D");
}
public static void printf(String msg, String... strs) {
int i = 0;
char[] chars = msg.toCharArray();
for ( char c : chars) {
System.out.print(c == '%' ? strs[i++] : c);
}
System.out.println();
}
}
C:\tiger>javac -d c:\tiger\cls\ c:\tiger\src\*.Java
C:\tiger>Java -classpath c:\tiger\cls tigers.FormatPrint
BITAN, HELEN, KATHY and SUSAN are my frIEnds!
A, B, C, D and Exception in thread "main" Java.lang.ArrayIndexOutOfBoundsException: 4
at tigers.FormatPrint.printf(FormatPrint.Java:12)
at tigers.FormatPrint.main(FormatPrint.Java:6)