在Java中,format函数是用于格式化字符串的方法,可以通过以下方式使用:
使用格式化字符串:%sString 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.
使用格式化数字:%d, %f, %e, %xint 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.
使用格式化日期:%tDate now = new Date();String message = String.format("Today is %tF.", now);System.out.println(message);输出:Today is 2022-01-01.
以上是format函数的基本用法,你可以根据具体需求来使用不同的格式化字符串。

