用java写万年历
时间: 2023-12-30 11:05:35 浏览: 82
java Android万年历
好的,以下是用Java实现的万年历代码:
```java
import java.util.Scanner;
public class Calendar {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年份:");
int year = scanner.nextInt();
System.out.print("请输入月份:");
int month = scanner.nextInt();
int[][] calendar = new int[6][7];
int days = getDaysOfMonth(year, month);
int firstDayOfWeek = getFirstDayOfWeek(year, month);
int day = 1;
for (int i = 0; i < 6; i++) {
for (int j = firstDayOfWeek; j < 7 && day <= days; j++) {
calendar[i][j] = day;
day++;
}
firstDayOfWeek = 0; // 每行第一个元素的列索引是0
}
System.out.println("\n\t\t" + year + "年" + month + "月");
System.out.println("\t日\t一\t二\t三\t四\t五\t六");
for (int i = 0; i < 6; i++) {
System.out.print((i+1) + "\t");
for (int j = 0; j < 7; j++) {
if (calendar[i][j] != 0) {
System.out.print(calendar[i][j] + "\t");
} else {
System.out.print("\t");
}
}
System.out.println();
}
}
/**
* 获取指定年月的天数
* @param year 年份
* @param month 月份(1-12)
* @return 天数
*/
public static int getDaysOfMonth(int year, int month) {
int days;
switch (month) {
case 2:
days = year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ? 29 : 28;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
default:
days = 31;
}
return days;
}
/**
* 获取指定年月第一天是星期几
* @param year 年份
* @param month 月份(1-12)
* @return 星期几(0-6,0表示星期日)
*/
public static int getFirstDayOfWeek(int year, int month) {
int century = year / 100;
year %= 100;
int dayOfWeek = (year + year/4 + century/4 - 2*century + 26*(month+1)/10) % 7;
if (dayOfWeek < 0) {
dayOfWeek += 7;
}
return dayOfWeek;
}
}
```
代码中,首先从控制台读取用户输入的年份和月份,然后根据输入的年月计算出当月的天数和第一天是星期几,最后使用一个二维数组来保存日历中的日期,并输出到控制台。
阅读全文