Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

How to override toString() properly in Java?

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...