编程题目:
7.输入某年某月某日,判断这一天是这一年的第几天?
示例代码:
package program.calculation.exercise07;
import java.util.Scanner;
/**
* 7.输入某年某月某日,判断这一天是这一年的第几天?
* 概念:
* 闰年:1.能被4整除而不能被100整除;(如2004年就是闰年,1800年不是。)
* 2.能被400整除。(如2000年是闰年。)
* 闰年二月份29天,而平年二月份28天。
* 分析:以4月4日为例,应该先把前三个月的加起来,然后再加上4天即本年的第几天,
* 特殊情况,闰年且输入月份大于3时需考虑多加一天。
*/
public class DayJudge {
public static void main(String[] args) {
System.out.println("请输入某年某月某日,以空格区分:");
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int year = scanner.nextInt();
int month = scanner.nextInt();
int day = scanner.nextInt();
System.out.println("输入的日期为:"+year+"年"+month+"月"+day+"日");
System.out.println("该日期是一年的第"+calculateDays(year, month, day)+"天");
}
//计算天数
private static int calculateDays(int year, int month, int day) {
int days = 0;
int[] months = null;
int[] month1 = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};//平年月份天数
int[] month2 = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};//闰年月份天数
if((0 == year%400)||(0 == year%4 && 0 != year%100)) { //判断是否是平年还是闰年
months = month2;
}else {
months = month1;
}
if(12<month || 1>month){ //判断输入月份是否合法
System.out.print("输入月份为非法月份!");
System.exit(-1); //退出程序
}
//判断输入月份天数是否合法
if((months[0]<day||months[2]<day||months[4]<day||months[6]<day
||months[7]<day||months[9]<day||months[11]<day)
&& (month==1||month==3||month==5||month==7||month==8||month==10||month==12)) {
System.out.print("输入日期为非法日期,此月份最多有"+months[0]+"天!");
System.exit(-1);
}
if((day>months[3]||day>months[5]||day>months[8]||day>months[10])
&& (month==4||month==6||month==9||month==11)){
System.out.println("输入非法日期,该月份最多有"+months[3]+"天!");
System.exit(-1);
}
if(months[1]<day) {
System.out.print("输入日期为非法日期,此月份最多有"+months[1]+"天!");
System.exit(-1);
}
for (int i=0; i<month-1; i++) { //将前几个月份天数相加
days += months[i];
}
return days+day; //再加上本月天数返回
}
}