> 文档中心 > Java实现万年历【初级】

Java实现万年历【初级】


目的:编写万年历,将之前的分支、循环语句结合使用,有利于巩固前面所学。通过编写一些“好玩的小项目”可以提高学习java的兴趣。

需求:输入年和月,输出当月的日历(1900年1月1日是星期一)

需要对平年还是闰年进行判断,需要对空格进行

空格为4

 空格为5

直接码源码

import java.util.Scanner;public class Test01{public static void main(String[] args){/**编写万年历需求:输入年和月,输出当月的日历(1900年1月1日是星期一)*/Scanner scan = new Scanner(System.in);System.out.println("请输入年:");int year = scan.nextInt();//2022System.out.println("请输入月:");int month = scan.nextInt();//3//计算1900年~输入年的总天数int allDayOfYear = 0;for(int i = 1900;i<year;i++){if(i%4==0 && i%100!=0 || i%400==0){//闰年allDayOfYear+=366;}else{//平年allDayOfYear+=365;}}//计算1月~输入月的总天数int allDayOfMonth = 0;for(int i = 1;i<month;i++){switch(i){case 1:case 3:case 5:case 7:case 8:case 10:case 12:allDayOfMonth += 31;break;case 4:case 6:case 9:case 11:allDayOfMonth += 30;break;case 2:if(year%4==0 && year%100!=0 || year%400==0){//闰年allDayOfMonth += 29;}else{//平年allDayOfMonth += 28;}break;}}//计算总天数int allDay = allDayOfYear + allDayOfMonth + 1;//计算星期int week = allDay%7;//计算当月的天数int day = 0;switch(month){case 1:case 3:case 5:case 7:case 8:case 10:case 12:day = 31;break;case 4:case 6:case 9:case 11:day = 30;break;case 2:if(year%4==0 && year%100!=0 || year%400==0){//闰年day += 29;}else{//平年day += 28;}break;}//打印日历System.out.println(" ---" + year + "年" + month + "月--- ");System.out.println("一\t二\t三\t四\t五\t六\t日");//打印日期前的空格int num = 0;//记录是否换行for(int i = 1;i<week;i++){System.out.print("\t");num++;}//打印日期的空格for(int i = 1;i<=day;i++){num++;System.out.print(i + "\t");if(num%7 == 0){System.out.println();}}}}

运行结果:

与实际相符:

 总结:

代码只是为了熟悉分支、循环语句,可能需要改进、精炼。仅供参考!!!