我应该制作一个包含方法和字符串格式的程序。情况是用户输入一个新的Tree示例:Tree t = new Tree(27,43.25,“Pine”)然后键入t.describe()并接收此输出 “树数27的周长为43.25,属于Pine。”
这是我的代码:
public class Tree{
int serial;
double circumference;
String species;
Tree(int serial, double circumference, String species) {
this.serial = serial;
this.circumference = circumference;
this.species = species;
}
public String describe() {
String.format("Tree number %d has a circumference of %.2f and is of species %s.", serial, circumference, species);
return describe();
}
}
该计划刚刚爆炸。 谢谢你的帮助!
答案 0 :(得分:6)
问题是你在describe()
内呼叫describe()
,并没有阻止它无限制地调用自己。您必须获得StackOverflowError
。
此处的解决方案很简单 - String.format
会返回您想要的String
。回来吧。
return String.format("Tree number %d has a circumference of %.2f and is of species %s.",
serial, circumference, species);
此外,请勿使用describe()
与describe()
联系。这就是它“爆炸”的原因。