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

哪位大神教教我啊
2024-11-26 06:33:27
推荐回答(2个)
回答1:

#include
void main()
{
int y,m,d;
int sum=0;
int flog;//标识是否是闰年
printf("请输入年月日(yyyy-mm-dd)\n");
scanf("%4d-%2d-%2d",&y,&m,&d);
if(( y%4==0 && y%100!=0 ) || y%400==0)
flog=1;
else
flog=0;
while((y<0)||(m>12||m<0)||(d<0||d>31)||((m%2==0)&&(d==31))||((flog==1)&&(m==2)&&(d>28)))
{
printf("input errro!\n");
printf("请输入年月日(yyyy-mm-dd)\n");
scanf("%4d-%2d-%2d",&y,&m,&d);
}
switch (m-1)
{
case 12: sum+=31;
case 11: sum+=30;
case 10: sum+=31;
case 9: sum+=30;
case 8: sum+=31;
case 7: sum+=31;
case 6: sum+=30;
case 5: sum+=31;
case 4: sum+=30;
case 3: sum+=31;
case 2:
if(flog==1) //这里改一下
sum+=28;
else
sum+=30;
case 1: sum+=31;break; //这里加上一个break语句
default:printf("非法月份\n");
break;
}
sum=sum+d;
if(flog==1)
printf("%d is leap year!\n",y);
printf("这一天是这年的第%d天",sum);
}
根据你的意思,修改了一下程序!你看看!

回答2:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Scanner;

public class GetDate {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年:");
int year = scanner.nextInt();
System.out.println("请输入月:");
int month = scanner.nextInt();
System.out.println("请输入日:");
int day = scanner.nextInt();
Calendar calendar1 = Calendar.getInstance();
calendar1.set(year, 0, 1);
long time1 = calendar1.getTimeInMillis();
Calendar calendar2 = Calendar.getInstance();
calendar2.set(year, month - 1, day);
long time2 = calendar2.getTimeInMillis();
long result = (time2 - time1) / 1000 / 60 / 60 / 24;
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(format.format(calendar2.getTime()) + "距离"
+ format.format(calendar1.getTime()) + "有" + result + "天");
}
}