/**
* Computes and returns the Date on which Thanksgiving will fall
* in a given year.
*
* NOTE: By law, Thanksgiving is the 4th Thursday in November
*
* @param year the year for which to compute the date of Thanksgiving
* @return the Date of Thanksgiving for the specified year
*/
public Date getThanksgiving(int year)
{
int weekcount = 0 ; // record the amount of weeks that has passed
Date thanksgiving = new Date (11 , 1 , year) ;
while ( weekcount < 4 )
{
thanksgiving.next(); // add one to date
if (thanksgiving.getDayOfWeek().equals("Thursday"))// check if the day of week is Thursday
{
weekcount++ ; // add one to weekcount
}
if (weekcount == 4)
{
System.out.println(thanksgiving.getLongDate());
}
}
return thanksgiving ;
}
我不应该使用println语句而应该使用return语句返回正确的日期。问题是我得到了这个&#34; Date @ 2f4d3709&#34;作为我的输出。 日期类 - http://users.cis.fiu.edu/~shawg/2210/Date.html
答案 0 :(得分:1)
如果您尝试拨打PrintStream.println()
with an Object
argument,该对象将使用Object.toString()
转换为String
。由于您的Date
课程未覆盖toString()
,因此将使用java.lang.Object
提供的默认实施。
你可以解决这三种方式。
Date.getLongDate()
方法并将返回的值传递给输出,而不是整个对象。getThanksgiving(int)
的返回值更改为字符串并返回Date.getLongDate()
toString()
课程中的Date
,如下所示。示例:
@Override
public String toString(){
return getLongDate();
}
答案 1 :(得分:1)
您的方法返回Date
个对象,由于您的类中未实现toString()
,因此打印对象的格式将为&#34; Date @ 2f4d3709&#34;在做某事时
System.out.println(getThanksgiving(2014));
相反,您必须调用getLongDate()
来获取要格式化的字符串
System.out.println(getThanksgiving(2014).getLongDate());