Add Properties to string”翻译为“将属性添加到字符串中”,可以通过以下方式实现:
定义一个类,并在类中定义属性。
使用StringBuilder类将属性转换为字符串,并添加到StringBuilder对象中。
将StringBuilder对象转换为字符串,并返回字符串。
代码示例:
public class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("姓名:" + name + "\n");
sb.append("年龄:" + age + "\n");
sb.append("性别:" + gender + "\n");
return sb.toString();
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person("Tom", 18, "男");
String s = p.toString();
System.out.println(s);
}
}