题目:输入某年某月某日,判断这一天是这一年的第几天?
程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。
闰年2月有29天,全年共有366天。普通闰年是指公历年份是4的倍数的,且不是100的倍数,世纪闰年则必须是400的倍数。
第一种:
public class Time {
public static void main(String[] args) {
int year;
int mouth;
int day=0;
int days;
//累计天数
int d=0;
int e = 0;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("输入年:");
year = scanner.nextInt();
System.out.println("输入月:");
mouth = scanner.nextInt();
System.out.println("输入日:");
days = scanner.nextInt();
if (mouth < 0 || mouth > 12 || days < 0 || days > 31) {
System.out.println("input error!");
e = 1;
}
} while (e == 1);
for (int i = 1; i <mouth; i++) {
switch (i) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: {
day = 31;
break;
}
case 4:
case 6:
case 9:
case 11: {
day = 30;
break;
}
case 2: {
/**
* 闰年:①:非整百年数除以4,无余为闰,有余为平;②整百年数除以400,无余为闰有余平
* 二月:平年28天、闰年29天
*/
if ((year % 100 !=0 &&year % 4 == 0) || (year % 100 == 0 && year%400==0)) {
day = 29;
} else {
day = 28;
}
}
default:
break;
}
d+=day;
}
System.out.println("这是"+year+"年的"+(d+days)+"天");
}
}
第二种:
import java.util.*;
public class Main3{
public static void main(String args[]){
int a ,sum = 0;
boolean leap = false ,b = false;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年 月 日,以空格隔开:");
a = scanner.nextInt();
if(a > 2 && a <= 12)
b = true;
if(a % 4 == 0 && a % 100 != 0 || a % 400 == 0)
leap = true;
a = scanner.nextInt();
switch(a){
case 2 : sum = 31;break;
case 3 : sum = 59;break;
case 4 : sum = 90;break;
case 5 : sum = 120;break;
case 6 : sum = 151;break;
case 7 : sum = 181;break;
case 8 : sum = 212;break;
case 9 : sum = 243;break;
case 10 : sum = 273;break;
case 11 : sum = 304;break;
case 12 : sum = 334;break;
default : System.out.println("error");
}
a = scanner.nextInt();
sum += a;
if(leap && b)
sum ++;
System.out.println("您输入的日期是该年第" + sum + "天");
}
}
第三种:
import java.util.*;
public class test {
public static void main (String[]args){
int day=0;
int month=0;
int year=0;
int sum=0;
int leap;
System.out.print("请输入年,月,日\n");
Scanner input = new Scanner(System.in);
year=input.nextInt();
month=input.nextInt();
day=input.nextInt();
switch(month) /*先计算某月以前月份的总天数*/
{
case 1:
sum=0;break;
case 2:
sum=31;break;
case 3:
sum=59;break;
case 4:
sum=90;break;
case 5:
sum=120;break;
case 6:
sum=151;break;
case 7:
sum=181;break;
case 8:
sum=212;break;
case 9:
sum=243;break;
case 10:
sum=273;break;
case 11:
sum=304;break;
case 12:
sum=334;break;
default:
System.out.println("data error");break;
}
sum=sum+day; /*再加上某天的天数*/
if(year%400==0||(year%4==0&&year%100!=0))/*判断是不是闰年*/
leap=1;
else
leap=0;
if(leap==1 && month>2)/*如果是闰年且月份大于2,总天数应该加一天*/
sum++;
System.out.println("It is the the day:"+sum);
}
}