import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestControl {
static int year, monthDay, weekDay;
//判断是否为润年
public static boolean isLeapYear(int y) {
return ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0);
}
//获取该年第一天为星期几
public static int firstDay(int y) {
long n = y * 365;
//公元元年到现在的润年
for (int i = 1; i < y; i++) {
if (isLeapYear(i)) {
n += 1;
}
}
return (int) n % 7;
}
//打印星期头
public static void printWeek() {
System.out.println("======================================================");
System.out.println("日\t一 \t二\t三 \t四 \t五 \t六");
}
//返回月的天数
public static int getMonthDay(int m) {
switch (m) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
default:
return 0;
}
}
//打印月历
public static void printMonth(){
for (int m = 1; m <= 12; m++){
System.out.println(m + "月");
printWeek();
for (int j = 1; j <= weekDay; j++){
System.out.print("\t");
}
int monthDay = getMonthDay(m);
for (int d = 1; d <= monthDay; d++){
System.out.print(d + "\t");
weekDay = (weekDay + 1) % 7;
if (weekDay == 0){
System.out.println();
}
}
System.out.println("\n");
}
}
public static void main(String[] args) throws IOException {
System.out.println("请输入一个年份:");
InputStreamReader ir =new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
String s = br.readLine();
year = Integer.parseInt(s);
weekDay = firstDay(year);
System.out.println("\n\t\t\t "+ year + "年 ");
printMonth();
}
}
java实现输入指定年打印该年日历练习
最新推荐文章于 2021-02-24 15:20:35 发布