欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

判断闰年及其星期几

发布时间:2024/5/15 编程问答 34 豆豆
生活随笔 收集整理的这篇文章主要介绍了 判断闰年及其星期几 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

输入年月日的值(均为整型数),输出该年份是否为闰年,同时输出该日期为星期几。 其中:年份的合法取值范围为[1820,2020] ,月份合法取值范围为[1,12] ,日期合法取值范围为[1,31] ; 判断星期几的算法如下:假定公元0001年1月1日为星期一,因此只要计算出当前输入日期离0001年1月1日所差的天数,然后拿这个天数除以7求余数,当余数为0时,为星期日,当余数为1时,为星期一,以此类推,当余数为6时,为星期六。
要求:Main类中必须含有如下方法,签名如下:
public static void main(String[] args);//主方法;
public static boolean isLeapYear(int year) ;//判断year是否为闰年,返回boolean类型;
public static int numOfDays(int year,int month ,int day) ;//求出year-month-day到0001-1-1的距离天数,返回整型数;
public static String getWhatDay(int days) ; //根据天数返回星期几,其中参数days为天数,整型数,返回星期几的英文单词。

注意:不允许使用Java中和日期相关的类和方法。
输入格式:
在一行内输入年月日的值,均为整型数,可以用一到多个空格或回车分隔。
输出格式:
当输入数据非法及输入日期不存在时,输出“Wrong Format”;
当输入日期合法,以如下格式输出两行数据(注意,两行末尾均有个.)
第一行:年份(值) is a leap year.
第二行:年-月-日(均为变量值) is 星期几(输出为星期日到星期六的英文单词).
输入样例1:
在这里给出一组输入。例如:
2020 3 9

输出样例1:
在这里给出相应的输出。例如:
2020 is a leap year.
2020-3-9 is Monday.

输入样例2:
在这里给出一组输入。例如:
1835 12 31

输出样例2:
在这里给出相应的输出。例如:
1835 is not a leap year.
1835-12-31 is Thursday.

输入样例3:
在这里给出一组输入。例如:
1999 9 31

输出样例3:
在这里给出相应的输出。例如:
Wrong Format
代码块:

import java.util.Scanner;public class Main {public static boolean isLeapYear(int year) {boolean isLeapYear = (year % 4 == 0 && year % 100 !=0 )||year % 400 == 0;return isLeapYear;}public static int numOfDays(int year,int month ,int day) {int days=0;int i ;int []aa = new int[]{0,31,28,31,30,31,30,31,31,30,31,30,31};for(i=1;i<year;i++){if(i%4==0&&i%100!=0||i%400==0) {days+=366;}else days+=365;}if((year % 4 == 0 && year % 100 !=0 )||year % 400 == 0) aa[2]=29;for(i = 1;i<month;i++){days+=aa[i];}days+=day;return days;}public static String getWhatDay(int days) {if(days%7==0) {return "Sunday";}else if(days%7==1) {return "Monday";}else if(days%7==2) {return "Tuesday";}else if(days%7==3) {return "Wednesday";}else if(days%7==4) {return "Thursday";}else if(days%7==5) {return "Friday";}else return "Saturday";}public static int format(int year,int month,int day){int Format=0;int[] mon1=new int[]{0,31,29,31,30,31,30,31,31,30,31,30,31};int[] mon2=new int[]{0,31,28,31,30,31,30,31,31,30,31,30,31};if(year>=1820&&year<=2020){if(month>0&&month<=12){ if(isLeapYear(year)){if(day<=mon1[month]&&day>0)Format=1;}else{if(day<=mon2[month]&&day>0)Format=1;}} }return Format;}public static void main(String[] args) {Scanner LJY = new Scanner(System.in);Main ljy = new Main();int year = LJY.nextInt();int month = LJY.nextInt();int day = LJY.nextInt();int days = numOfDays(year,month ,day);if(format(year,month,day)==1) {if(ljy.isLeapYear(year)) {System.out.println(year+" is a leap year.");System.out.println(year+"-"+month+"-"+day+" is "+ljy.getWhatDay(days)+".");}else {System.out.println(year+" is not a leap year.");System.out.println(year+"-"+month+"-"+day+" is "+ljy.getWhatDay(days)+".");}}else System.out.println("Wrong Format");}}

总结

以上是生活随笔为你收集整理的判断闰年及其星期几的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。