万年历方法二

时间:2022-03-03 13:14:08
import java.util.Scanner;
import javax.management.RuntimeErrorException;
public class PrintCalendar {
public static void main(String[] args) {
int month = 0;
int day = 0;
int sumdays = 0;
int yearday = 0;
int monthday = 0;
int week = 0;
int weekday = 0;
String answer;
Scanner sc = new Scanner(System.in);
System.out.println("**************欢迎使用万年历************");
System.out.println("请输入年份");
int year = sc.nextInt();
System.out.print("请输入月份:");
month = sc.nextInt();

//判断月份输入是否合法
if (month <= 0 || month > 12) {
throw new RuntimeErrorException(null, "月份输入错误");
} else {
boolean isRn = year % 4 == 0 && year % 100 != 0 || year % 400 == 0; //判断是否为闰年
//判断每一个月都有多少天
if (month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month == 10 || month == 12) {
day = 31;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
day = 30;
} else if (month == 2 && isRn == true) {
day = 29;
} else {
day = 28;
}
//1900年一月一日 周一
//计算到当前年份的前一年一共有多少天
for (int i = 1900; i < year; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
yearday = yearday + 366;
} else {
yearday = yearday + 365;
}
}
//计算到当前月份的前一个月一共有多少天
for (int n = 1; n < month; n++) {
if (n == 1 || n == 3 || n == 5 || n == 7 || n == 8 || n == 10
|| n == 12) {
monthday = monthday + 31;
} else if (n == 4 || n == 6 || n == 9 || n == 11) {
monthday = monthday + 30;
} else if (n == 2 && isRn == true) {
monthday = monthday + 29;
} else {
monthday = monthday + 28;
}
}
//System.out.println("1900年1月:"+monthday);
sumdays = yearday + monthday;
//if(sumday%7!=0){
week = 1 + sumdays % 7;
//}else{
// week = sumdays%7
//}
System.out.println(week);
System.out.println("日\t一\t二\t三\t四\t五\t六");
if (week != 7) {
for (int j = 0; j < week; j++) {
System.out.print("\t");
}
}
for (int k = 1; k <= day; k++) {
weekday = (sumdays - 1 + k) % 7 + 1;
if (weekday == 6) {
System.out.print(k + "\n");
} else {
System.out.print(k + "\t");
}
}
}
}
}