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
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 calling this is below
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
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.
Help?
As you can see above, we can override the toString() method of the Student class to get a meaningful presentation of the object. In conclusion, it's a good idea to override toString() , as we get proper and customized output when an object is used.
What you get is an instance type. We already have a method to get the type of the Object GetType() that the Object class has provided and ToString() is doing the exact same thing but that will not help. This is the reason we should override ToString() to provide our own implementation.
Override the toString() method in a Java Class A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.
The toString
is supposed to return a String
.
public String toString() { return "Name: '" + this.name + "', Height: '" + this.height + "', Birthday: '" + this.bDay + "'"; }
I suggest you make use of your IDE's features to generate the toString
method. Don't hand-code it.
For instance, Eclipse can do so if you simply right-click on the source code and select Source > Generate toString
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With