-2

我问过你GregorianCalendarCalendar有些人说这样Calendar更好。所以我在Calender课堂上做到了。

我对一种方法有疑问:JavaApplication1#whichIsEarlier(),总是收到错误。请检查一下,如果可以的话。如何解决?我会感谢你的帮助。

 public class JavaApplication1 {


public static void main(String[] args) {
    Calendar yy =Calendar.getInstance();
    Calendar xx= Calendar.getInstance();
    xx.set(2001, 10,10);
    Data dt = new Data(yy);
    Data xt = new Data(xx);
    Data dd = new Data( yy, xx);
    System.out.println(dt.toString());
    System.out.println(xt.toString());       
    System.out.println(dd.whichIsEarlier());
}
}


class Data {
    private Calendar calendar;
     Calendar cale;
    Data(Calendar x){

    calendar = x;
}

Data(Calendar x, Calendar y){
    calendar = x;
    cale = y;
}

public String toString(){ 
    String months[] = {"Jan","Feb", "Mar" , "Apr", "Mai", "June", "July","Aug",
        "Sep", "Okt", "Nov", "Dec"};
    String str = "";
    str = "Data: "+ calendar.get(Calendar.DATE) +" "+ months[calendar.get(Calendar.MONTH)]+
        " "+ calendar.get(Calendar.YEAR);
        return str;

    }

    public String whichIsEarlier(Calendar cale){
        String str = "";
        if(calendar.after(cale)) str = calendar.toString() ;
        else str = cale.toString();
        return str +" jest wczesniej";
    }
 }
4

2 回答 2

0
System.out.println(dd.whichIsEarlier());

是有问题的,因为您只定义 a Data#whichIsEarlier(Calender)

请确保whichIsEarlier调用传入一个日历对象,或者您创建一个whichIsEarlier不带参数且预定义日历的新对象。

于 2013-08-24T08:50:09.593 回答
0

这就是我清理您的代码的方式:

class Data {
  private Calendar calendar;

  Data(Calendar x) { calendar = x; }

  public String whichIsEarlier(Data other) {
    return (calendar.after(other.calendar)? this : other)
        + " jest wczesniej";
  }

(我已经省略toString了;我没有为这个答案讨论它的问题)。

笔记:

  • 删除了cale实例变量
  • 删除了两个参数的构造函数;
  • whichIsEarlier接受另一个Data,而不是另一个Calendar
  • 它的返回值不是调用calendar.toString而是调用你自己对象的 toString
  • 它隐式地做到了(字符串连接做到了)。

现在主要方法应该像

public static void main(String[] args) {
  Calendar yy =Calendar.getInstance();
  Calendar xx= Calendar.getInstance();
  xx.set(2001, 10,10);
  Data dt = new Data(yy);
  Data xt = new Data(xx);
  System.out.println(dt.whichIsEarlier(xt));
}
于 2013-08-24T09:01:55.060 回答