Tôi thích nghĩ về trường hợp thử nghiệm. Giá trị nào cho beginDate
và endDate
sẽ gây ra một phương thức trả về đúng hay sai?
Ví dụ: nếu chúng ở cùng năm? Có lẽ cả hai giá trị đều nằm trên cùng một bên của ngày 29 tháng 2 hoặc chúng có chiều dài.
Điều gì xảy ra nếu chúng ở các năm khác nhau? Điều gì xảy ra nếu những năm đó liền kề, hoặc nếu có những năm khác ở giữa? Có lẽ không có năm can thiệp nào thậm chí là năm nhuận.
Sau đó, bạn có thể làm gì trong trường hợp này được đặt cùng các ví dụ về các trường hợp này và sau đó viết một phương thức, điều chỉnh nó cho đến khi tất cả các xác nhận vượt qua.
Dưới đây là cách tiếp cận bạn có thể thực hiện. Bạn có thể muốn thêm các trường hợp trong đó beginDate
và/hoặc maturity
vào một ngày nhuận.
public class Q26403911 {
@Test
public void testContainsLeapYear() throws Exception {
Assert.assertTrue(isContainsLeapYear(LocalDate.of(1984, 2, 28), LocalDate.of(1984, 3, 1)));
Assert.assertFalse(isContainsLeapYear(LocalDate.of(1985, 2, 28), LocalDate.of(1985, 3, 1)));
Assert.assertFalse(isContainsLeapYear(LocalDate.of(1984, 2, 27), LocalDate.of(1984, 2, 28)));
Assert.assertFalse(isContainsLeapYear(LocalDate.of(1984, 3, 1), LocalDate.of(1984, 3, 2)));
Assert.assertTrue(isContainsLeapYear(LocalDate.of(1984, 2, 28), LocalDate.of(1985, 3, 1)));
Assert.assertTrue(isContainsLeapYear(LocalDate.of(1983, 3, 1), LocalDate.of(1984, 3, 1)));
Assert.assertFalse(isContainsLeapYear(LocalDate.of(1984, 3, 1), LocalDate.of(1985, 3, 1)));
Assert.assertFalse(isContainsLeapYear(LocalDate.of(1983, 2, 28), LocalDate.of(1984, 2, 28)));
Assert.assertTrue(isContainsLeapYear(LocalDate.of(1983, 3, 1), LocalDate.of(1985, 2, 28)));
Assert.assertFalse(isContainsLeapYear(LocalDate.of(1985, 3, 1), LocalDate.of(1987, 2, 28)));
}
public boolean isContainsLeapYear(LocalDate beginDate, LocalDate maturity) {
if (beginDate.getYear() == maturity.getYear())
{
if (!Year.isLeap(beginDate.getYear()))
{
return false;
}
if (maturity.isBefore(LocalDate.of(beginDate.getYear(), Month.FEBRUARY, 29)))
{
return false;
}
if (beginDate.isAfter(LocalDate.of(maturity.getYear(), Month.FEBRUARY, 29)))
{
return false;
}
return true;
}
else if (Year.isLeap(beginDate.getYear())
&& !beginDate.isAfter(LocalDate.of(beginDate.getYear(), Month.FEBRUARY, 29)))
{
return true;
}
else if (Year.isLeap(maturity.getYear())
&& !maturity.isBefore(LocalDate.of(maturity.getYear(), Month.FEBRUARY, 29)))
{
return true;
}
else
{
for (int year = beginDate.getYear() + 1; year < maturity.getYear(); year++)
{
if (Year.isLeap(year))
{
return true;
}
}
}
return false;
}
}
Chỉ cần kiểm tra ngày cuối cùng của tháng hai tháng – Roshan
Có một thời gian Joda hoặc java 8 lần api câu hỏi? Câu trả lời có thể khác ... – assylias
@assylias Java 8. Cảm ơn :-) – YvesHendseth