gpt4 book ai didi

java - 计算数组中周末天数记录

转载 作者:行者123 更新时间:2023-11-30 06:36:38 25 4
gpt4 key购买 nike

我有一个字符串数组,其中包含从 CSV 文件读取的日期。
现在我想计算该数组中有多少个周末。但是在我的数组中有一些日期是重复的。这里显示了我的数组中包含的部分数据。

12/2/2010
12/3/2010
12/5/2010
12/10/2010
12/5/2010
12/13/2010
12/14/2010
12/12/2010

在这个数据集中12/5/2010 is Sunday(但有两条记录)& 12/12/2010 is Saturday(有一条记录)。在输出中,我想使用 java 打印此数组中的周末天数。与此示例相比,答案应为 2

FileInputStream fis=new FileInputStream("c:/cdr2.csv");
InputStreamReader isr=new InputStreamReader(fis);
BufferedReader bf = new BufferedReader(isr);
while (bf.ready()) {
String line = bf.readLine();
String[] values=line.split(",");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/d/yyyy");
Date date = simpleDateFormat.parse(values[2]);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
}

最佳答案

首先,您需要编写一个方法来确定给定的 Date 是否是周末:

public static boolean isWeekend(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
return dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY;
}

然后,你需要定义一个DateFormat , 这样您就可以将日期 String 解析为 java.util.Date。最后,您可以使用 Set确保您发现的每个周末都不会重复:

public static void main(String[] args) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String[] dates = { "12/2/2010", "12/3/2010", "12/5/2010", "12/10/2010", "12/5/2010", "12/13/2010", "12/14/2010", "12/12/2010" };
Set<String> weekends = new HashSet<String>();
for (String dt : dates) {
Date date = dateFormat.parse(dt);
if (isWeekend(date)) {
weekends.add(dt);
}
}
System.out.println("There are " + weekends.size() + " distinct weekends."); // 2
}

关于java - 计算数组中周末天数记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4647703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com