英文:
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>
专注分享java语言的经验与见解,让所有开发者获益!
评论