题目类别: 实验
关键字: Java基本语法 输入输出 算术运算 关系运算 选择语句 循环语句
内容要求:
编写程序,实现如下功能:
提示用户输入一个年份和代表该年第一天是星期几的数字。说明星期日到星期六用0-6表示。
程序依次输出该年的每个月的日历。
运行实例:
输入年份: 2017
该年第1天是星期几: 0
备注
提交要求:包含源程序文件的JAR
实现代码:
package Calendar;
import java.util.Scanner;
/**
* @Author zg
*/
public class ShowCalendar {
/**
* 用于衔接上个月与下一个月
*/
public static int TEMP;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("输入年份: ");
int year = sc.nextInt();
System.out.print("该年第1天是星期几(星期日到星期六用0-6表示): ");
int day = sc.nextInt();
sc.close();
print(year, day);
}
/**
* 是否为闰年
*/
public static boolean isLeapYear(int year) {
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
/**
* 遍历打印日历
*/
public static void print(int year, int day) {
TEMP = day;
int dayCount; //每月的天数
for (int i = 0; i < 12; i++) {
System.out.println(String.format("%4d", year) + "年" + String.format("%2d", i + 1) + "月");
// 基于Java8, 高版本Java可以使用增强switch
switch (i + 1) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: {
//大月31天
dayCount = 31;
TEMP %= 7;
monthPrint(dayCount);
break;
}
case 2: {
//特殊月份
if (isLeapYear(year)) {
dayCount = 29;
} else {
dayCount = 28;
}
TEMP %= 7;
monthPrint(dayCount);
break;
}
default: {
//小月30天
dayCount = 30;
TEMP %= 7;
monthPrint(dayCount);
}
}
}
}
public static void monthPrint(int dayCount) {
System.out.println("---------------------------");
System.out.println("Sun Mon Tue Wed Thu Fri Sat");
// 每月的日历所占行数
int row = TEMP + dayCount > 35 ? 6 : 5;
int[][] array = new int[6][7];
for (int j = TEMP, count = 1; count <= dayCount; j++, TEMP++, count++) {
array[j / 7][j % 7] = count;
}
for (int j = 0; j < row; j++) {
for (int k = 0; k < 7; k++) {
if (array[j][k] != 0) {
if (k == 0) {
// 首列占3个字符的位置
System.out.printf("%3d", array[j][k]);
} else {
// 3个字符的位置+1个字符位置的间隔
System.out.printf("%4d", array[j][k]);
}
} else {
if (k == 0) {
// 首列占3个字符的位置
System.out.print(" ");
} else {
// 3个字符的位置+1个字符位置的间隔
System.out.print(" ");
}
}
}
System.out.println();
}
System.out.println("---------------------------");
}
}
附:
于2021/10/18 17:11 修改了
switch
中的内容,因为之前使用的JDK15
(支持增强switch
);现在使用JDK8
。JDK8
不支持增强switch
,于是进行了此次修改。