Java 创建返回字符串的方法
到目前为止,我的代码如下所示:Java 创建返回字符串的方法,java,Java,到目前为止,我的代码如下所示: public class Tree { public static void main (String[] argv) { int serial; //create parameters double circumference; String species; } public Tree(int serial, double circumference, String species) { String.f
public class Tree {
public static void main (String[] argv) {
int serial; //create parameters
double circumference;
String species;
}
public Tree(int serial, double circumference, String species) {
String.format("Tree number %d has a circumference of %.2f and is of species %s.",
serial, circumference, species);
}
}
我不确定如何制作一个
descripe()
方法,该方法返回一个字符串,其中包含非常特定格式的树信息。该方法String.format
已经返回了一个字符串
public String describe(){
return String.format("Tree number %d has a circumference of %.2f and is of species %s.", serial, circumference, species);
}
我建议您重写toString()
方法,以提供有关对象的有意义信息
public String toString(){
return String.format("Tree number %d has a circumference of %.2f and is of species %s.", serial, circumference, species);
}
您试图将descripe方法代码放入树构造函数中。不要那样做。使用构造函数初始化字段,然后创建返回格式化字符串的descripe方法
public class Tree {
// private Tree fields go here
public Tree(int serial, double circumference, String species) {
// initialize the Tree fields here
}
public String describe() {
// return your formatted String describing the current Tree object here
}
}
顺便说一句,您的main方法实际上没有做任何有用的事情,当然也不会创建任何允许您测试descripe方法的树实例。很抱歉,您的代码很难看,这意味着它的格式很差,很难阅读。至少对我来说,如果你花一些精力来更好地格式化你的代码,使用合理一致的缩进和最少但适当地使用空白(一个空行就足够了),更多的人将能够阅读和理解你的代码,然后帮助你。请相信我,这是很好的付出。String[]result=myTreeSet.toArray(新字符串[myTreeSet.size()]);然后转换为字符串