输入年月日的值(均为整型数),输出该年份是否为闰年,同时输出该日期为星期几。 其中:年份的合法取值范围为[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)
{
int n;
if((year%4==0&&year%100!=0)||year%400==0)
{
return true;
}
else
{
return false;
}
}
public static int numOfDays(int year,int month ,int day)
{
int[] a=new int[13];
a[1]=31;
a[2]=28;
a[3]=31;
a[4]=30;
a[5]=31;
a[6]=30;
a[7]=31;
a[8]=31;
a[9]=30;
a[10]=31;
a[11]=30;
a[12]=31;
int t=0;
for(int i=1;i<year;i++)
{
if(isLeapYear(i)==true)
{
t+=366;
}
else
{
t+=365;
}
}
for(int i=1;i<month;i++)
{
t+=a[i];
}
t+=day;
return t;
}
public static String getWhatDay(int days)
{
String s=null;
if(days%7==0)
{
s="Sunday";
}
if(days%7==1)
{
s="Monday";
}
if(days%7==2)
{
s="Tuesday";
}
if(days%7==3)
{
s="Wednesday";
}
if(days%7==4)
{
s="Thursday";
}
if(days%7==5)
{
s="Friday";
}
if(days%7==6)
{
s="Saturday";
}
return s;
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int year,month,day;
year=in.nextInt();
month=in.nextInt();
day=in.nextInt();
boolean n=isLeapYear(year);
if(year>=1820&&year<=2020&&month>=1&&month<=12&&day>=1&&day<=31)
{
if(n==true)
{
System.out.printf("%d is a leap year.\n",year);
if((month==7||month==8)&&day==31||(month==12&&day==31)||(month==4&&day==30))
{
int days=numOfDays(year,month,day);
String week=getWhatDay(days+1);
System.out.println(year+"-"+month+"-"+day+" is "+week+".");
System.exit(0);
}
}
else
{
if(month==2&&day==29)
{
System.out.println("Wrong Format");
System.exit(0);
}
else
System.out.printf("%d is not a leap year.\n",year);
}
int days=numOfDays(year,month,day);
String week=getWhatDay(days);
System.out.println(year+"-"+month+"-"+day+" is "+week+".");
}
else
{
System.out.println("Wrong Format");
}
}
}
该博客介绍如何在不使用Java日期相关类的情况下,判断一个年份是否为闰年,并计算给定日期距离公元0001年1月1日的天数,从而确定是星期几。提供了一个主方法和三个辅助方法,包括isLeapYear()用于判断闰年,numOfDays()计算天数差,getWhatDay()获取星期几的英文单词。
2178





