java中法定假期天数总和,(蓝桥杯)java模拟题第九题-计算天数

(蓝桥杯)java模拟题第九题---------计算天数

从键盘输入一个日期,格式为yyyy-M-d

要求计算该日期与1949年10月1日距离多少天

例如:

用户输入了:1949-10-2

程序输出:1

用户输入了:1949-11-1

程序输出:31

/**

* @category 1949-10-1到输入日期之间一共有多少天

* @author liucanwen

* @2012年1月17日 20:59:27

*

*/

public class CountDays

{

public static void main(String[] args)

{

try

{

System.out.print("请输入日期,格式如1949-10-2:");

Scanner scanner = new Scanner(System.in);

String date = scanner.nextLine();

int year = Integer.parseInt(date.split("-")[0]);

int month = Integer.parseInt(date.split("-")[1]);

int day = Integer.parseInt(date.split("-")[2]);

System.out.println(CountDays.countDays(year, month, day));

}

catch(Exception ex)

{

System.out.println("你输入日期的格式不正确。");

}

}

/**

* @param year 输入的年

* @param month 输入的月

* @param day 输入的日

* @return 天数

*/

public static int countDays(int year, int month, int day)

{

//闰年、平年每月的天数

int[][] days={{31,28,31,30,31,30,31,31,30,31,30,31},

{31,29,31,30,31,30,31,31,30,31,30,31}};

//用index标识是什么年,index=0:平年,index=1:闰年

int index = year%4==0 && year%100!=0 || year%400==0? 1: 0;

//判断输入日期是否正确

if(year<1949 || month<1 || month>12 || day<1 || day>days[index][month-1])

return -1;

int[] years = {365, 366};

//1949-10-1到1950-1-1剩余的天数

int otherDays = 92;

//用于统计日期离1949-10-1有多少天

int count = 0;

//如果输入year为1949

if(1949 == year)

{

if(10 < month)

{

return -1;

}

if(10 == month)

{

count = day - 1;

}

else if(11 == month)

{

count = days[0][9] + day - 1;

}

else if(12 == month)

{

count = days[0][9] + days[0][10] + day - 1;

}

}

//如果输入year大于1949

else

{

//如果输入year等于1950

if(year - 1949 == 1)

{

for(int i = 0; i < month - 1; i++)

{

count += days[index][i];

}

count = count + otherDays + day - 1;

}

//如果输入year大于1950

else

{

for(int i = 1950; i < year; i++)

{

int index2 = i%4==0 && i%100!=0 || i%400==0? 1: 0;

count += years[index2];

}

for(int i = 0; i < month - 1; i++)

{

count += days[index][i];

}

count = count + otherDays + day - 1;

}

}

return count;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值