gpt4 book ai didi

java - 查找指定年份中给定工作日的次数

转载 作者:行者123 更新时间:2023-12-01 07:48:28 25 4
gpt4 key购买 nike

我正在尝试编写一个需要两个参数的程序:工作日和年份。然后,程序应该打印出用户指定的工作日落在给定年份的每个月的第一天的次数。我可以做一个月,但我如何迭代所有十二个月。

这是我的代码:

public class dateCheck {

public static void main(String[] args) {

String weekday="Sunday";
int year=2017;

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, 01);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.YEAR, year);

cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDayOfMonth = cal.getTime();

DateFormat sdf = new SimpleDateFormat("EEEEEEEE");
System.out.println("First Day of Month: " + sdf.format(firstDayOfMonth));

if(weekday.equals(sdf.format(firstDayOfMonth))){
System.out.println("This day falls on the first of the month");
}
else
System.out.println("This day does not fall on the first of the month");


}


}

我想我可以使用 for 循环,但我不知道如何迭代几个月。我是 Java 新手。任何帮助表示赞赏。谢谢。

最佳答案

如果您能够使用 Java 8,就没有理由继续使用日历。这是使用 new Date and Time api 的版本:

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.Locale;

public class WeekdayCheck {

public static void main(String[] args) {
String weekday = "Sunday";
int year = 2017;
int occurrences = 0;

for (Month month : Month.values()) {
LocalDate date = LocalDate.of(year, month, 1);
DayOfWeek dayOfWeek = date.getDayOfWeek();
if (dayOfWeek.getDisplayName(TextStyle.FULL, Locale.ENGLISH).equals(weekday)) {
occurrences++;
}
}

System.out.println(weekday + " is the first day of a month " + occurrences + " times in " + year);
}
}

更新:

初始版本使用 dayOfWeek.getDisplayName 与您的比较一致。更明智的选择(如评论中所指出的)是将用户输入也转换为 DayOfWeek 实例。

这是一种修改后的方法,目前适用于“sunday”、“Sunday”或“sUnDaY”等输入,但可以通过增强 toDayOfWeek 方法进行调整以获得更复杂的逻辑:

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

public class WeekdayCheck {

public static void main(String[] args) {
String userInput = "Sunday";
DayOfWeek inputDayOfWeek = toDayOfWeek(userInput);
int inputYear = 2017;
int occurrences = 0;

for (Month month : Month.values()) {
LocalDate date = LocalDate.of(inputYear, month, 1);
DayOfWeek dayOfWeek = date.getDayOfWeek();
if (dayOfWeek == inputDayOfWeek) {
occurrences++;
}
}

System.out.println(userInput + " is the first day of a month " + occurrences + " times in " + inputYear);
}

private static DayOfWeek toDayOfWeek(String dayString) {
return DayOfWeek.valueOf(dayString.toUpperCase());
}
}

关于java - 查找指定年份中给定工作日的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44186933/

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