Question

I have asked you about GregorianCalendar and Calendar and some people said that Calendar is better. So I did it with Calender class.

I have a problem with one method: JavaApplication1#whichIsEarlier(), always receives error. Please check it, if you can. How to resolve it? I'll appreciate your help.

 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";
    }
 }
Was it helpful?

Solution

This is how I would clean up your code:

class Data {
  private Calendar calendar;

  Data(Calendar x) { calendar = x; }

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

(I have elided toString; I'm not getting into its issues for this answer).

Note:

  • removed the cale instance variable
  • removed the two-argument constructor;
  • whichIsEarlier accepts another Data, not another Calendar;
  • its return value doesn't call calendar.toString but rather your own object's toString
  • and it does it implicitly (string concatenation does that).

And now the main method should go like

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));
}

OTHER TIPS

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

is problematic as you only define a Data#whichIsEarlier(Calender).

Please make sure that either the whichIsEarlier call passes in a calendar object, or you create a new whichIsEarlier that takes no arguments and has calendars predefined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top