构造函数没有设置值?获取方法不起作用

时间:2014-03-10 23:55:20

标签: java

这是对我之前问题的修改,因为每个建议都无法解决主要问题。在我的程序中,由于某种原因,monthName,year和day的值在程序期间消失。此Test程序的输出为null,0,0。顺便说一句,LongDate继承自Date类,而不是java.util.Date,而是我创建的类,editDay和editYear是Date类中列出的方法。

非常感谢。任何提示赞赏。

public class Test {

public static void main(String[] args) {

    //creates an array of type Date filled with two LongDate objects

    Date [] collectionOfDates = { new LongDate("February",2,1996), new LongDate("February",13,1999) };

    // loops through the array and displays output of getDate() for each object

    for( int i = 0; i < collectionOfDates.length; i++ ) {

        System.out.println( collectionOfDates[i].getDate() );

    }

}

}

这是LongDate类:

public class LongDate extends Date {

private String monthName;
private int day;
private int year;

public LongDate(String m, int d, int y) {       

    super.editDay(d);
    super.editYear(y);
    editMonth(m);

}

public void setDate(String m, int d, int y) {

    monthName = m;
    day = d;
    year = y;

}


public String getDate() {

    StringBuilder fullDate = new StringBuilder();
    fullDate.append(monthName);
    fullDate.append(" ");
    fullDate.append(day);
    fullDate.append(", ");
    fullDate.append(year);

    return fullDate.toString();
}

public String getShortDate() {

    int month = 0;

    if (monthName.equals("January")) {
        month = 1;
    } else if (monthName.equals("February")) {
        month = 2;
    } else if (monthName.equals("March")) {
        month = 3;
    } else if (monthName.equals("April")) {
        month = 4;
    } else if (monthName.equals("May")) {
        month = 5;
    } else if (monthName.equals("June")) {
        month = 6;
    } else if (monthName.equals("July")) {
        month = 7;
    } else if (monthName.equals("August")) {
        month = 8;
    } else if (monthName.equals("September")) {
        month = 9;
    } else if (monthName.equals("October")) {
        month = 10;
    } else if (monthName.equals("November")) {
        month = 11;
    } else if (monthName.equals("December")) {
        month = 12;
    }

    StringBuilder shortDate = new StringBuilder();
    shortDate.append(month);
    shortDate.append("/");
    shortDate.append(day);
    shortDate.append("/");
    shortDate.append(year);

    return shortDate.toString();
}

protected String editMonth(String m) {

    // asks person to try again if month is not capitalized and spelled properly
    if (!m.equals("January") && !m.equals("February") && !m.equals("March") && !m.equals("April") && !m.equals("May") && !m.equals("June") && !m.equals("July") && !m.equals("August") && !m.equals("September") && !m.equals("October") && !m.equals("November") && !m.equals("December")) {
        m = Input.getString( "Invalid month. Please type the month again." );
        return m;       
    } else
        return m;
}
}

0 个答案:

没有答案