Java-检查数组是否包含3个连续的日期 [英] Java - Check if array contains 3 consecutive dates

查看:259
本文介绍了Java-检查数组是否包含3个连续的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个String []数组,其中包含格式为YYYY/MM/DD的日期.我想遍历此数组,看看数组中的下2个元素是否包含连续的日期.如果确实如此,则只需增加count变量即可.到目前为止,这就是我所拥有的.我只是基本上需要有关if语句的帮助,该语句检查是否有3个连续的日期.

Hi I have a String[] array that contains dates in the format YYYY/MM/DD. I want to iterate through this array and see if the next 2 elements in the array contain consecutive dates. If they do then just increase the count variable. Here is what I have so far. I just basically need help regarding the if statement that checks if there are 3 consecutive dates.

int count = 0;

String[] dates = { 
        "2004/1/23", "2004/1/24", "2004/1/25",
        "2004/1/26", "2004/1/29", "2004/2/11", 
        "2004/2/17", "2004/2/18", "2004/2/18", "2004/3/7"};

for(int i = 0; i < dates.length-2; i++){

    //Help needed here! If i, i+1 and i+2 are consecutive...
    if(...){
        count++;
    }
}

我意识到我可能需要先将String日期转换为实际的Date对象,然后才能进行比较.进一步的指导将不胜感激.谢谢

I realise that I might need to convert the String dates into an actual Date object before I can compare them. Further guidance would be appreciated. Thanks

推荐答案

String[]转换为Date[](即,准备一个Date数组).我想您已经知道该怎么做.

Convert String[] to Date[] (i.e., prepare a Date array). I presume you already know how to do this.

现在您可以使用以下类似的方法检查连续的日期:

Now you can check for consecutive dates with something like this:

Calendar c = Calendar.getInstance();
int numConsecutive = 0;
Date last = null;

for (int i = 0; i < dates.length; i++) {
    c.setTime(dates[i]);
    c.add(Calendar.DATE, -1);
    if (c.getTime().equals(last)) {
        numConsecutive++;
    } else {
        numConsecutive = 0;
    }
    if (numConsecutive == 2) {
        numConsecutive = 0;
        count++;
    }
    last = dates[i];
}

这篇关于Java-检查数组是否包含3个连续的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆