java input a date and determine the day of the year
- 2020-06-15 08:33:32
- OfStack
Topic: Input a day of a year, determine the day is the day of this year?
Program analysis: take March 5 as an example, should first add up the first two months, and then add 5 days that is the day of the current year, special case, leap year and input month more than 3 when you need to consider an additional day.
Program design:
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(" Please enter the year , month , day \n");
Scanner input = new Scanner(System.in);
year=input.nextInt();
month=input.nextInt();
day=input.nextInt();
switch(month) /* Calculate the total number of days before a 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; /* Plus the number of days on a given day */
if(year%400==0||(year%4==0&&year%100!=0))/* Decide if it's a leap year */
leap=1;
else
leap=0;
if(leap==1 && month>2)/* If it's a leap year and the month is greater than 2, The total number of days should be added 1 day */
sum++;
System.out.println("It is the the day:"+sum);
}
}