What is wrong with my logic?

This is a java code, but the error is logic error so I guess I can get help here.
So basically what my code do below is to check whether a given date is before or after the specific date.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
   public boolean isBefore(Date d) {
    if (this.year < d.year){
    	return true;
    }
    if (this.year == d.year){
    	if (this.month < d.month){
    		return true;
    	}
    	if(this.month == d.month){
    		if (this.day < d.day){
    			return true;
    		}
    	}
    }
    return false;
  }

  /** Determines whether this Date is after the Date d.
   *  @return true if and only if this Date is after d. 
   */
  public boolean isAfter(Date d) {
    if (isBefore(d) == false){
    	if ((this.month != d.month) & (this.year != d.year) & (this.day != d.day)){
    		return true;
    	}
    }
    return false;
	  
  }

I passed all the test except one.

1/1/1976 after 12/31/1975 should be true: true
1/2/1976 after 1/1/1976 should be true: false <-- my code should output true but instead it output false. Why? Where's my logic error?
12/31/1975 after 12/31/1975 should be false: false
12/31/1975 after 1/1/1976 should be false: false
1/1/1976 after 1/2/1976 should be false: false
12/31/1975 before 1/1/1976 should be true: true
1/1/1976 before 1/2/1976 should be true: true
12/31/1975 before 12/31/1975 should be false: false
1/1/1976 before 12/31/1975 should be false: false
1/2/1976 before 1/1/1976 should be false: false



You don't check for the month being greater than. It's always false irrespective of the result of the day comparison.
^
1
2
3
4
if (this.year == d.year){
    	if (this.month < d.month){
    		return true;
    	}


you mean this line? If year is the same, we need to check whether the month is greater. What's wrong?
Last edited on
^
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
   public boolean isBefore(Date d) {
      if (this.year < d.year) {
         return true;
      }
      else if (this.year > d.year) {
         return false;
      }

      if (this.month < d.month) {
         return true;
      }
      else if (this.month > d.month) {
         return false;
      }

      return this.day < d.day;
  }
Topic archived. No new replies allowed.