Java – LocalDate comparison out of range but incorrect output

huangapple go评论72阅读模式
英文:

Java - LocalDate comparison out of range but incorrect output

问题

package test;

import java.time.LocalDate;

public class A1 {
	
	public void searchEnrolments(int StartDay, int StartMonth, int StartYear, int EndDay, int EndMonth, int EndYear) {
	 	   LocalDate a = LocalDate.of(StartYear, StartMonth, StartDay);
	 	   LocalDate b = LocalDate.of(EndYear, EndMonth, EndDay);   
		   boolean before = a.isBefore(b);
		   if (before = true) {
				   System.out.println("超出范围:");
				   }
	 	  else {
	 			 System.out.println("无效日期范围");
	 		   }
		  }
}
package test;
public class aTester {
	public static void main(String[] args) {
		A1 a2= new A1();
		a2.searchEnrolments(20, 04, 2020, 10, 02, 2019);
	}
}
英文:

Im trying to compare two dates against a list of dates (list element has been removed as it would require more classes provided so i am just giving the base requirements for it to run)

The two dates the list is comparing to is a date range to identify objects which are within this range

When two CORRECT dates are provided as a range the output is fine

the problem occurs when an incorrect range is provided (end date is before start date) an invalid date range is not outputted

package test;

import java.time.LocalDate;

public class A1 {
	
	public void searchEnrolments(int StartDay, int StartMonth, int StartYear, int EndDay, int EndMonth, int EndYear) {
	 	   LocalDate a = LocalDate.of(StartYear, StartMonth, StartDay);
	 	   LocalDate b = LocalDate.of(EndYear, EndMonth, EndDay);   
		   boolean before = a.isBefore(b);
		   if (before = true) {
				   System.out.println("Out of range: ");
				   }
	 	  else {
	 			 System.out.println("Invalid Date Range");
	 		   }
		  }
}

package test;
public class aTester {
	public static void main(String[] args) {
		A1 a2= new A1();
		a2.searchEnrolments(20, 04, 2020, 10, 02, 2019);
	}
}

答案1

得分: 0

这是因为您没有使用"=="等于运算符。您正在在if条件中进行赋值操作。

只需替换if条件部分:

if (before == true) {
    System.out.println("超出范围:");
} else {
    System.out.println("无效日期范围");
}
}
英文:

This is happening because you are not using "==" equals opeator. You are assigning the value in the if-clause.

Just replace the if clause-

 if (before == true) {
                   System.out.println("Out of range: ");
                   }
          else {
                 System.out.println("Invalid Date Range");
               }
          } 

</details>



huangapple
  • 本文由 发表于 2020年4月5日 17:48:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/61040736.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定