2

所以我尝试在网上进行研究,我觉得它是我的 toString(),但它在某种程度上是正确的,我想不出任何其他方式。

我希望能够输出:Lexie-高度:2.6 英尺。出生日期:2009 年 11 月 5 日

我的代码如下所示:

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) { 
        StringTokenizer st = new StringTokenizer(date, "/", true);
        n = this.name;
        h = this.height;
    } 
    /**
    public String toString() { 
        return (this.name + ", Height: " + this.height + "ft., Born: "
        + this.month + "/" + this.day + "/" + this.year);
    } 
    */
    public String toString() {
        Calendar currentDate = Calendar.getInstance();
        return (this.name + ", Height: " + this.height + "ft., Born: "
        + this.bDay);
    }
} //end class 

调用 Kid 类如下

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
4

3 回答 3

6

您在构造函数中的表达式是错误的方式 - 你有n = this.name你应该有的地方this.name = n。同样对于this.height。此外,您当前根本没有设置该bDay字段。因此所有领域确实是null

于 2012-05-29T14:58:50.630 回答
1

试试这个:

public Kid (String n, double h, String date) { 
        StringTokenizer st = new StringTokenizer(date, "/");
        this.name = n;
        this.height = h;
        this.bDay = new GregorianCalendar(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
    }
于 2012-05-29T15:03:32.630 回答
0

尝试修改您的构造函数和 bDay 的类型:

private static final String DATE_FORMAT = "dd/MM/yyyy";
String name; 
double height; 
Date bDay; 

public Kid () { 
    this.name = "HEAD";
    this.height = 1; 
    this.bDay = new Date(); 
} 

public Kid (String n, double h, String date) { 
    DateFormat df = new SimpleDateFormat(DATE_FORMAT);
    this.bDay = df.parse(date);
    this.name = n;
    this.height = h;
} 

public String toString() {
    DateFormat df = new SimpleDateFormat(DATE_FORMAT);
    return (this.name + ", Height: " + this.height + "ft., Born: "
    + df.format(this.bDay));
}
于 2012-05-29T15:03:17.807 回答