关于java编写简易版 控制台输出万年历
输入月份和年 在控制台输出万年历 结果图如下: 代码`
package example;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// 定义总天数
int sum = 0;
// 输入的年份
int year = 0;
// 输入的月份
int month = 0;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("请输入年份:");
year = sc.nextInt();
boolean inputYearIsTrue = CalendarUtils.judgeInputYear(year);
if (inputYearIsTrue) {
break;
}
}
while (true) {
System.out.println("请输入月份:");
month = sc.nextInt();
boolean inputMonthIsTrue = CalendarUtils.judgeInputMonth(month);
if (inputMonthIsTrue) {
break;
}
}
sum = getSumYearDays(year);
// 总天数得减去多遍历的那个月份的天数
sum = sum + 1 - getSumMonthDays(year, month);
int monthDay = getCurrentMonthDays(year, month);
// 除以7便是从那天开始
int length = sum % 7;
System.out.println("日 一 二 三 四 五 六");
// 之前用空格 打印
for (int i = 0; i <= length - 1; i++) {
System.out.print(" ");
}
// 遍历月份monthDay
for (int i = 1; i <= monthDay; i++) {
if (sum % 7 == 6) {
System.out.print(i + "
");
} else {
System.out.print(i + " ");
}
// 总天数自增
sum++;
}
}
/**
* 获取总的年份天数
*
* @param year
* 输入的年份
* @return 年份的天数
*/
public static int getSumYearDays(int year) {
int sum = 0;
// 遍历年份的天数
for (int i = 1900; i < year; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
sum += 366;
} else {
sum += 365;
}
}
return sum;
}
/**
* 获取月份总的天数 不包括当前的月份
*
* @param year
* 输入的月份
* @return 月份的天数
*/
public static int getSumMonthDays(int year, int month) {
int monthSum = 0;
for (int i = 1; i < month; i++) {
monthSum += getCurrentMonthDays(year, i);
} // for循环结束 遍历月份的天数。
return monthSum;
}
/**
* 获取当前月份的天数
*
* @param year
* 输入的月份
* @return 月份的天数
*/
public static int getCurrentMonthDays(int year, int month) {
int monthDay = 0;
// 当为闰年时月份
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
if (month == 2) {
monthDay = 29;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
monthDay = 30;
} else {
monthDay = 31;
}
} else {
// 当为平年时
if (month == 2) {
monthDay = 28;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
monthDay = 30;
} else {
monthDay = 31;
}
}
return monthDay;
}
}
class CalendarUtils {
public static boolean judgeInputYear(int year) {
return year < 1900 ? false : true;
}
public static boolean judgeInputMonth(int month) {
return (month <= 0 || month > 12) ? false : true;
}
}
