如何在Java中正确覆盖toString()? [英] How to override toString() properly in Java?
问题描述
听起来有点愚蠢,但我需要帮助我的 toString()
方法,这非常令人讨厌。
我尝试在网上查询,因为 toString
是一个搞砸了,没有找到Kid构造函数#2,即使它在那里,我会甚至做其他事情,但它不起作用。
好的很多,所以这里是我的代码:
Sounds a little stupid, but I need help on my toString()
method and it is very irking.
I tried looking up online because the toString
is the one where it is screwing up and "not finding Kid constructor #2" even though it is there and I would even do something else and it doesn't work.
Ok that was a lot so here is my code:
import java.util.*;
class Kid {
String name;
double height;
GregorianCalendar bDay;
public Kid () {
this.name = "HEAD";
this.height = 1;
this.bDay = new GregorianCalendar(1111,1,1);
}
public Kid (String n, double h, String date) {
// method that toString() can't find somehow
StringTokenizer st = new StringTokenizer(date, "/", true);
n = this.name;
h = this.height;
}
public String toString() {
return Kid(this.name, this.height, this.bDay);
}
} //end class
好的我上面的toString(我知道,我的第三个参数是关闭的,应该是一个String)关闭。如果我硬编码第三件事的价值就会变得混乱,并说它找不到这个(上面的)。那么我该如何获取日期并将其分解?
Ok So my toString above (I know, my third parameter is off, should be a String) is off. If I hardcode a value in for the third thing it goes haywire and says it can't find this (up above). So how can I get the date and break it up?
调用此类的课程在
class Driver {
public static void main (String[] args) {
Kid kid1 = new Kid("Lexie", 2.6, "11/5/2009");
System.out.println(kid1.toString());
} //end main method
} //end class
我试过研究多个构造函数,它确实没有帮助。
我尝试研究 toString()
方法,并尝试使用我创建的先前 toString()
方法逻辑以前,但这是全新的,所以它从来没有奏效。
I tried researching multiple constructors and it really didn't help.
I tried researching toString()
methods, and tried using previous toString()
methods logic that I created previous but this is brand new so it never worked.
帮助?
推荐答案
toString
应返回 String
。
public String toString() {
return "Name: '" + this.name + "', Height: '" + this.height + "', Birthday: '" + this.bDay + "'";
}
我建议您利用IDE的功能生成 toString
方法。不要手工编写代码。
I suggest you make use of your IDE's features to generate the toString
method. Don't hand-code it.
例如,如果只需右键单击源代码并选择 Source>,Eclipse就可以这样做;生成toString
For instance, Eclipse can do so if you simply right-click on the source code and select Source > Generate toString
这篇关于如何在Java中正确覆盖toString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!