生活随笔
收集整理的這篇文章主要介紹了
判断闰年及其星期几
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
輸入年月日的值(均為整型數),輸出該年份是否為閏年,同時輸出該日期為星期幾。 其中:年份的合法取值范圍為[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");}}
總結
以上是生活随笔為你收集整理的判断闰年及其星期几的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。