有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Return语句没有以正确的格式返回输出

/**
 * 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语句返回正确的日期。问题是我得到了这个“Date@2f4d3709“作为我的输出。 日期类--http://users.cis.fiu.edu/~shawg/2210/Date.html


共 (1) 个答案

  1. # 1 楼答案

    如果试图调用^{} with an ^{} argument,则该对象将使用^{}转换为String。由于Date类不重写toString(),因此将使用java.lang.Object提供的默认实现

    你可以用三种方法解决这个问题

    1. 您需要调用Date.getLongDate()方法并将返回的值传递给输出,而不是整个对象
    2. getThanksgiving(int)的返回值更改为字符串并返回Date.getLongDate()
    3. Date类中重写toString(),如下所示

    例如:

    @Override
    public String toString(){
      return getLongDate();
    }