在Java中,format函數是用于格式化字符串的方法,可以通過以下方式使用:
String name = "John";
int age = 30;
String message = String.format("My name is %s and I'm %d years old.", name, age);
System.out.println(message);
輸出:My name is John and I’m 30 years old.
int number = 10;
String message = String.format("The number is %d.", number);
System.out.println(message);
float pi = 3.14159f;
String message = String.format("The value of pi is %.2f.", pi);
System.out.println(message);
double exponent = 1.23456789e+5;
String message = String.format("The exponent value is %e.", exponent);
System.out.println(message);
int hexNumber = 255;
String message = String.format("The hexadecimal number is %x.", hexNumber);
System.out.println(message);
輸出: The number is 10. The value of pi is 3.14. The exponent value is 1.234568e+05. The hexadecimal number is ff.
Date now = new Date();
String message = String.format("Today is %tF.", now);
System.out.println(message);
輸出:Today is 2022-01-01.
以上是format函數的基本用法,你可以根據具體需求來使用不同的格式化字符串。