练习14

来源:互联网 发布:网络构架 编辑:程序博客网 时间:2024/06/13 04:37

题目:输入某年某月某日,判断这一天是这一年的第几天。


分析:每年除了二月,其他月份的天数都是固定的,而在闰年,二月有29天,不是闰年二月只有28天。把每个月的总天数存到一个数组中。计算这一天是这一年的第几天需要把这个月之前的月的天数加起来,再加上这一天的日数,结果就是所要求的天数。需要注意的是,当输入的年月日小于0,或者月大于12,日大于31,还有闰年2月的日大于29,非闰年2月的日大于28时,输入都是错误的,不能输出结果。


代码:
import java.util.*;public class Practice14 {public static void main(String[] args){Scanner data = new Scanner(System.in);System.out.println("请输入年:");int year = data.nextInt();  //输入年System.out.println("请输入月:");int month = data.nextInt();  //输入月System.out.println("请输入日:");int day = data.nextInt();  //输入日int d = 0;  //定义这一天是这一年的第d天boolean b = true;  //判断输入日期是否正确if((year < 0) || (month < 0) || (month > 12) || (day < 0) || (day > 31) || ((year % 400 == 0) || ((month == 2) && (day > 28)) || ((year % 100 != 0) && (year % 4 ==0)) && (month == 2) && (month > 29))){b = false;  //剔除错误输入System.out.println("输入日期有误");}if(b == true){d = countingDays(year,month,day);  //调用countingDays()方法计算天数System.out.println("这一天是这一年的第" + d +"天");}data.close();}public static int countingDays(int y, int m, int d){int ds = 0;  //定义总天数int mo[] = new int[13];  //定义数组mo[]存入每个月的天数,下标为月份,元素为天数mo[1] = 31;mo[3] = 31;mo[4] = 30;mo[5] = 31;mo[6] = 30;mo[7] = 31;mo[8] = 31;mo[9] = 30;mo[10] = 31;mo[11] = 30;mo[12] = 31;  //将每个月的天数存到数组中if((y % 400 == 0) || ((y % 100 != 0) && (y % 4 ==0))){mo[2] = 29;  //闰年的二月有29天}else{mo[2] = 28;  //非闰年的二月有28天}for(int i = 1; i < m; i++){ds += mo[i];  //把m月之前的月的天数加起来}ds = ds + d;  //得到最终的天数return ds;}}

结果:


原创粉丝点击