java日历程序
时间: 2023-12-10 19:40:35 浏览: 214
Java日历程序.zip
以下是一个简单的Java日历程序,它可以根据用户输入的年份和月份计算并显示一个月的日历:
```java
import java.util.*;
public class CalendarProgram {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter year (e.g. 2022): ");
int year = input.nextInt();
System.out.print("Enter month (1-12): ");
int month = input.nextInt();
// Create a Calendar object and set the year and month
Calendar cal = Calendar.getInstance();
cal.set(year, month-1, 1); // Note: months are 0-based in Calendar
// Get the number of days in the given month
int numDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
// Print the header for the calendar
System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
// Print the calendar
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
for (int i = 1; i < dayOfWeek; i++) {
System.out.print(" ");
}
for (int day = 1; day <= numDays; day++) {
System.out.printf("%4d", day);
if (dayOfWeek == 7) {
System.out.println();
dayOfWeek = 1;
} else {
dayOfWeek++;
}
}
System.out.println();
}
}
```
该程序首先要求用户输入一个年份和一个月份,然后使用Calendar类来计算该月的日历。程序首先获取该月的天数,然后打印日历的表头,并使用for循环打印日历中的每一天。程序在打印每一天之前会计算出该天是星期几,并根据需要插入一些空格来使日历排版正确。
阅读全文