java.lang.String.format()字符串格式化功能使用
时间: 2023-08-03 16:20:40 浏览: 98
Java中的String.format()方法可以将一个字符串格式化为指定格式。
该方法的语法为:
```
public static String format(String format, Object... args)
```
其中,format参数是格式化字符串,args参数是一个可变参数,可以传入任意数量的参数。
格式化字符串中可以包含占位符,用于指定要替换的值的位置和格式。占位符的格式为:%[标识][宽度][.精度]转换字符。
下面是一些常用的占位符:
- %s:字符串
- %d:十进制整数
- %f:浮点数
- %c:字符
- %b:布尔值
- %t:日期/时间
示例代码:
```java
String name = "John";
int age = 30;
double height = 1.75;
String message = String.format("My name is %s, I'm %d years old, and I'm %.2f meters tall.", name, age, height);
System.out.println(message);
```
输出结果为:
```
My name is John, I'm 30 years old, and I'm 1.75 meters tall.
```
相关问题
Static method format( java.lang.String, int ) not found in class'java.lang.String'
这个错误提示是因为 Java 中的 String 类并没有提供 `format(String format, int args)` 这个静态方法。
正确的 String.format() 方法的语法是这样的:
```
public static String format(String format, Object... args)
```
其中,format 参数是格式化字符串,args 参数是一个可变参数,可以传入任意数量的参数。
你可以使用类似于下面的代码来使用 String.format() 方法:
```java
int number = 42;
String message = String.format("The answer to the ultimate question of life, the universe, and everything is %d", number);
System.out.println(message);
```
输出结果为:The answer to the ultimate question of life, the universe, and everything is 42
请注意,第一个参数中的格式化字符串中需要使用 `%d` 占位符来代表要替换的整数类型参数,而不是直接传递一个整数参数。
java.sql.Timestamp cannot be cast to java.lang.String
这个错误通常发生在代码中将一个 `java.sql.Timestamp` 类型的对象尝试转换成一个 `java.lang.String` 类型时出现。
要解决这个问题,有两种方法:
1.使用 `Timestamp` 对象的 `toString()` 方法将其转换成字符串,例如:
```
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String strTimestamp = timestamp.toString();
```
2.使用 `SimpleDateFormat` 将 `Timestamp` 对象格式化成字符串,例如:
```
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
String strTimestamp = sdf.format(timestamp);
```
这两种方法都能将 `Timestamp` 对象转换成字符串,具体使用哪种方法取决于你的业务需求。