Java 我如何从一月到十二月的某一天
我是java新手,我正在努力争取2009年的第七天。 我有点不知道该怎么做。下面是我的代码Java 我如何从一月到十二月的某一天,java,Java,我是java新手,我正在努力争取2009年的第七天。 我有点不知道该怎么做。下面是我的代码 public class Main { public static void main(String[] args) { System.out.println("WELCOME TO MY CALENDER CLASS"); Calendar calendar = Calendar.getInstance(); calendar.set(DAY
public class Main {
public static void main(String[] args) {
System.out.println("WELCOME TO MY CALENDER CLASS");
Calendar calendar = Calendar.getInstance();
calendar.set(DAY_OF_MONTH,7);
calendar.set(Calendar.YEAR,2009);
for(int i =1; i <= 12; i++){
calendar.set(DAY_OF_MONTH,i);
System.out.println(calendar.getTime());
}
}
}
好的,假设你从1月1日开始,这里有一个简单的例子。我希望Java1.8代码对您来说是清晰的
public static void main(String[] args) {
// create two localdate start of a year instances, one for current year and one for next year, 2009 and 2010 respectively
LocalDate thisYear = LocalDate.of(2009, Month.JANUARY, 1);
LocalDate nextYear = LocalDate.of(2010, Month.JANUARY, 1);
// used only for counting number of every seventh day in a year
int i=0;
// while we are not in the next year, 2010
while (thisYear.isBefore(nextYear)) {
i++;
// print current date
System.out.println(i+" " + thisYear.toString());
// add a week or seven days to our thisYear instance and loop thru again
thisYear = thisYear.plusWeeks(1);
}
}
代码的问题在于,在
for
循环中,您为日历对象设置了日期而不是月份。
因此,请改为:
for(int i = 0; i < 12; i++){
calendar.set(Calendar.MONTH, i);
System.out.println(calendar.getTime());
}
您使用的Java版本是什么?您的代码有问题吗?请准确描述您试图实现的目标,以及您提供的代码无法按预期方式工作的原因。您是否尝试过在调试器中单步执行代码,以查看它与预期结果的偏差?Java 11.02版@LaksithaRanasinghaI希望在2009年的第7天@Jason
for(int i = 0; i < 12; i++){
calendar.set(Calendar.MONTH, i);
System.out.println(calendar.getTime());
}
System.out.println("WELCOME TO MY CALENDER CLASS");
LocalDate date;
for(int i = 1; i <= 12; i++){
date = LocalDate.of(2009, Month.of(i), 7);
System.out.println(date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));
}