如何在 Java 中檢查陣列中是否包含三個連續日期?


要檢查給定的陣列是否包含三個連續的日期

  • 將給定的陣列轉換為 LocalDate 型別的列表。
  • 使用 LocalDate 類的比較方法比較列表的 i、i+1 和 i+1、i+2 個元素,如果相等則列表包含 3 個連續的元素。

示例

線上演示

import java.time.LocalDate;
import java.time.Month;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class ConsicutiveDate {
   public static void main(String args[]) {
      String[] dates = {"5/12/2017", "6/12/2017", "7/12/2017"};
      List<LocalDate> localDateList = new ArrayList<>();
      for (int i = 0; i<dates.length; i++) {
         String[] data = dates[i].split("/");
         Month m = Month.of(Integer.parseInt(data[1]));
         LocalDate localDate =
            LocalDate.of(Integer.parseInt(data[2]),m,Integer.parseInt(data[0]));
         localDateList.add(localDate);
         Date date = java.sql.Date.valueOf(localDate);
      }
      System.out.println("Contents of the list are ::"+localDateList);
      Collections.sort(localDateList);
      for (int i = 0; i < localDateList.size() - 1; i++) {
         LocalDate date1 = localDateList.get(i);
         LocalDate date2 = localDateList.get(i + 1);
         if (date1.plusDays(1).equals(date2)) {
            System.out.println("Consecutive Dates are: " + date1 + " and " + date2);
         }
      }
   }
}

輸出

Contents of the list are ::[2017-12-05, 2017-12-06, 2017-12-07]
Consecutive Dates are: 2017-12-05 and 2017-12-06
Consecutive Dates are: 2017-12-06 and 2017-12-07

更新於: 2020-02-19

911 次瀏覽

開啟您的職業生涯

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.