为什么我的输出变为空值?

时间:2012-05-29 14:56:29

标签: java

所以我尝试在网上进行研究,我觉得这是我的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

3 个答案:

答案 0 :(得分:6)

你的构造函数中的表达式是错误的 - 你n = this.name应该有this.name = n。同样适用于this.height。此外,您当前还没有设置bDay字段。因此,所有字段都是null

答案 1 :(得分: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()));
    }

答案 2 :(得分: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));
}