两个班级问题

时间:2013-08-24 08:29:32

标签: java java.util.calendar

我问过你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";
    }
 }

2 个答案:

答案 0 :(得分:0)

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

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

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

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