如何在 Java 中正确覆盖 toString()? [英] How to override toString() properly in Java?

查看:42
本文介绍了如何在 Java 中正确覆盖 toString()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

听起来有点愚蠢,但我需要有关 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(我知道,我的第三个参数是关闭的,应该是一个字符串)是关闭的.如果我为第三件事硬编码一个值,它会失控并说它找不到这个(上面).那么我怎样才能得到日期并将其分解呢?

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.

例如,Eclipse 可以这样做,只要您只需右键单击源代码并选择 Source >生成toString

For instance, Eclipse can do so if you simply right-click on the source code and select Source > Generate toString

这篇关于如何在 Java 中正确覆盖 toString()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆