初学者,请帮看程序并优化,虽然实现了计算两个日期之间的天数,但是感觉总有问题。
import java.util.Scanner;class JiSuanTianShu//计算年份1到年份2之间的天数
{
public static void main (String [] args){
Scanner s = new Scanner(System.in);
System.out.print("请输入起始年:");
int y1 = s.nextInt();
System.out.print("请输入始年月:");
int m1 = s.nextInt();
System.out.print("请输入始年日:");
int d1 = s.nextInt();
System.out.print("请输入截止年:");
int y2 = s.nextInt();
System.out.print("请输入截止月:");
int m2 = s.nextInt();
System.out.print("请输入截止日:");
int d2 = s.nextInt();
int sum = 0 ;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
if(y1<y2)//判断起止年
{
//计算起止年之间整年的天数
for(int i= y1+1 ; i<y2 ;i++){
if(i%4==0&&i%100==00||i%400==0)
{ sum3 = sum3 + 366;
System.out.println(i+"年"+sum3+"天");}
else
{sum3 = sum3 + 365;
System.out.println(i+"年"+sum3+"天");}
}
//计算起始年剩余的天数。
switch(m1){
case 1:
sum1 = sum1+31;
case 2:
if(y1%4==0&&y1%100!=0||y1%400==0)
sum1 = sum1+29;
else
sum1 = sum1+28;
case 3:
sum1 = sum1+31;
case 4:
sum1 = sum1+30;
case 5:
sum1 = sum1+31;
case 6 :
sum1 = sum1+30;
case 7:
sum1 = sum1+31;
case 8:
sum1 = sum1+31;
case 9:
sum1 = sum1+30;
case 10:
sum1 = sum1+31;
case 11:
sum1 = sum1+30;
case 12 :
sum1 = sum1+31;
}
sum1 = sum1-d1;
System.out.println(y1+"年"+m1+"月"+d1+"日"+"之后"+y1+"年还剩余"+sum1+"天");
//计算截止年月日之前的天数。
switch(m2-1){
case 11:
sum2 = sum2+30;
case 10:
sum2 = sum2+31;
case 9:
sum2 = sum2+30;
case 8:
sum2 = sum2+31;
case 7:
sum2 = sum2+31;
case 6 :
sum2 = sum2+30;
case 5:
sum2 = sum2+31;
case 4:
sum2 = sum2+30;
case 3:
sum2 = sum2+31;
case 2:
{ if(y1%4==0&&y1%100!=0||y1%400==0)
sum2 = sum2+29;
else
sum2 = sum2+28;
}
case 1 :
sum2 = sum2+31;
}
sum2 = sum2+d2;
System.out.println(y2+"年"+m2+"月"+d2+"日是"+y2+"年的第"+sum2+"天。");
sum = sum1 +sum2+sum3;
System.out.println(y1+"年"+m1+"月"+d1+"日"+"到"+y2+"年"+m2+"月"+d2+"日有"+sum+"天。");
}else if(y1==y2)//同年则要判断是否月份大小以及日期大小
{
if(m1<=m2&&d1<=d2)
{
sum = sum1+d2-d1;
System.out.println(y1+"年"+m1+"月"+d1+"日"+"到"+y2+"年"+m2+"月"+d2+"日有"+sum+"天。");
}else if(d1>d2){
System.out.println("起止日期输入错误!");
}else
System.out.println("起止月份输入错误!");
}else
System.out.println("起止年份输入错误!");
}
}