参考 - P102~P103
1. 目标
生成一个日历,格式如下图所示。
ps: 当前的天数需要标记为*
2. 核心
对日历的变量
import java.time.*;
public class CalendarTest{public static void main(String[] args) {LocalDate date = LocalDate.now(); // 获取当前日期int month = date.getMonthValue(); // 获取当前月份int today = date.getDayOfMonth(); // 获取当前的天数date = date.minusDays(today - 1); // 将当前日期设置为月初while(date.getMonthValue() == month) { // 只要是当月就输出,否则跳出循环System.out.printf("%3d", date.getDayOfMonth());date = date.plusDays(1);}}
}
3. 实现
在核心部分实现了日历的循环打印,接下来只需要补全表头、当前日期和换行即可.
import java.time.*;public class CalendarTest{public static void main(String[] args) {LocalDate date = LocalDate.now();int month = date.getMonthValue();int today = date.getDayOfMonth();date = date.minusDays(today - 1); // 设置为本月的开头DayOfWeek weekday = date.getDayOfWeek(); // 获取星期几int value = weekday.getValue(); // 将星期几兑换成对应的数字System.out.println("Mon Tue Wed Thu Fri Sat Sun"); // 日历头for(int i = 1; i < value; i++) { // 打印对应的空格System.out.print(" ");}while(date.getMonthValue() == month) {System.out.printf("%3d", date.getDayOfMonth()); // 获取当前多少号if(date.getDayOfMonth() == today) {System.out.print("*");} else {System.out.print(" ");}date = date.plusDays(1);if(date.getDayOfWeek().getValue() == 1){System.out.println();}}if (date.getDayOfWeek().getValue() != 1) System.out.println();}
}