您现在的位置是:首页 > 文章详情

使用 java 基础语言实现万年历

日期:2019-08-02点击:414

已知(只有一个已知条件):

  • 1900年1月1号是星期一

实现的功能:

  • 通过本条件来写一个输入相应的年份和月份就可以在控制台输出相应月份月历

基本的思路:

  1. 已知1900年的1月1日是周一,要输出这个月的月历首先最需要知道的就是本月1号是周几,这样我们才可以排列出来这个月的月历第一天的位置

     本月1号距离1900年1月1号多少天设为days,这个天数对7取余数就可以求出本月1号是周几 0周一 | 1周二 | 2周三 |3 周四 | 4周五 | 5周六 | 6周日 天数 = (输入的年份 - 1900)* 365 (如果是闰年在加一天) 闰年的判断条件(可以被4整除但是不能被100整除的 或者 是可以被400整除的年份)
  2. 第二点就是要知道这个月有多少天

     本月的天数就是从1月份到12月份判断(中间要注意平年和閏年的2月份不一样,加一个条件判断) 
  3. 第三点就是每次要在周六的日期输出之后换到下一行(以周日为每周的第一天的情况)

     判断日期为周几的方法和判断1号的方法是一样的,为了方便可以直接在本月1号的时间上加上今天的日期减一就可以知道今天的时间 距离1900年1月1号的时间差,对7取余就知道是周几了 

下面是个人写的代码:

public class WanNianLi { public static void main(String[] args) { Scanner input = new Scanner(System.in); // 欢迎界面 System.out.println("*************************"); System.out.println("******** 万年历 *********"); System.out.println("*************************"); System.out.print("请输入年份:"); // 年份 int year = input.nextInt(); System.out.print("请输入月份:"); // 月份 int month = input.nextInt(); boolean isRun = year % 4 == 0 && year % 100 != 0 || year % 400 == 0; /** * 当前月份的月1日距离1900 年的1月1日多少日 */ int dates = 0; for (int i = 1900; i < year; i++) { dates += 365; //判断是不是闰年,如果是闰年就在dates的基础上+1天 if ((i % 4 == 0 && i % 100 != 00) || (i % 400 == 0)) { dates += 1; } // System.out.println(i + "年:" + dates); } // System.out.println(dates); // 1、3、5、7、8、10月份加31天,3、6、9、11月加30天,平年2月加28,闰年2月加29天 for (int i = 1; i < month; i++) { switch (i) { case 1: case 3: case 5: case 7: case 8: case 10: dates += 31; break; case 4: case 6: case 9: case 11: dates += 30; break; case 2: if (isRun) { dates += 29; } else { dates += 28; } break; } } // System.out.println(dates); System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六"); /** * 1号需要空几个制表符 */ int week = dates % 7; switch (week) { case 0: System.out.print("\t");// 周一 break; case 1: System.out.print("\t\t");// 周二 break; case 2: System.out.print("\t\t\t");// 周三 break; case 3: System.out.print("\t\t\t\t");// 周四 break; case 4: System.out.print("\t\t\t\t\t");// 周五 break; case 5: System.out.print("\t\t\t\t\t\t");// 周六 break; default: break; } /** * 选择输出的这个月的天数 */ int days = 31; switch (month) { case 4: case 6: case 9: case 11: days = 30; break; case 2: if (isRun) { days = 29; } else { days = 28; } break; } /** * 循环输出本月的每一天,判断如果是周六就换行 */ for (int i = 1; i <= days; i++) { System.out.print(i + "\t"); if ((dates + i - 1) % 7 == 5) { System.out.println(); } } } }

结果演示:

bandicam_2019_08_03_14_11_30_911
bandicam_2019_08_03_14_11_20_318

原文链接:https://yq.aliyun.com/articles/712414
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章