java 日历功能
- 功能概述
- java代码
- 打印结果
功能概述
输入年份和月份,打印该月份所有日期,头部信息为星期一至星期日
java代码
package com.java.core.demoTest;
import java.util.Calendar;
import java.util.Scanner;// 打印日历
public class CalendarDemo2 {public static void main(String[] args) {// 创建一个 Scanner 对象,用于接收用户输入Scanner scanner = new Scanner(System.in);// 提示用户输入年份System.out.print("请输入年份:");int year = scanner.nextInt();// 提示用户输入月份System.out.print("请输入月份:");int month = scanner.nextInt();// 创建一个 Calendar 对象,用于获取日历信息Calendar calendar = Calendar.getInstance();calendar.set(Calendar.YEAR, year);calendar.set(Calendar.MONTH, month - 1); // 将月份减1,因为Calendar的月份从0开始// 打印日历的头部信息System.out.println("一 二 三 四 五 六 日");int head = 0;int first = 0;String [][] arr = new String[5][7];// 打印日历的日期信息int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);for (int day = 1; day <= daysInMonth; day++) {calendar.set(Calendar.DAY_OF_MONTH, day);int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);if (dayOfWeek == 1) {arr[head][6] = String.valueOf(day);head++;} else {if (first == 0) {for (int i = 0; i < dayOfWeek - 2; i++) {arr[0][i] = "0";}}first++;arr[head][dayOfWeek -2] = String.format("%2d", day);}}for (int i = 0; i < arr.length; i++) {for (int j = 0; j < arr[i].length; j++) {if (null == arr[i][j]) {System.out.print("0" + " ");} else {System.out.print(arr[i][j] + " ");}}System.out.println(); // 换行}}
}