读书人

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

发布时间: 2012-09-07 10:38:15 作者: rapoo

(蓝桥杯)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为1949if(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大于1949else{//如果输入year等于1950if(year - 1949 == 1){for(int i = 0; i < month - 1; i++){count += days[index][i];}count = count + otherDays + day - 1;}//如果输入year大于1950else{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;}}

读书人网 >编程

热点推荐