import java.util.Scanner;
public class JSday {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("输入年");
int year=input.nextInt();
System.out.println("输入月");
int month=input.nextInt();
System.out.println("输入日");
int day=input.nextInt();
int tian=0;//存储闰年,平年2月天数
int ri = 0;//多少天
boolean i;
//先计算出润年,平年用存入tian
if((year%4==0&&year%100!=0)||year%400==0) {
i=true;
tian=29;
}else {
i=false;
tian=28;
}
//使用switch选择月份
switch(month) {
case 1:
ri=day;
tian=ri;
System.out.println("这是"+year+"的第"+ri+"天");
break;
case 2:
//如果2月有超过29天则报错
if(month==2 & i==true & day>29 ) {
System.out.println("天数错误");
}else {
ri=31+day;
System.out.println("这是"+year+"的第"+ri+"天");
}
break;
case 3:
ri=31+tian+day;
System.out.println("这是"+year+"的第"+ri+"天");
break;
case 4:
ri=31+tian+30+day;
System.out.println("这是"+year+"的第"+ri+"天");
break;
case 5:
ri=31+tian+30+31+day;
System.out.println("这是"+year+"的第"+ri+"天");
break;
case 6:
ri=31+tian+30+31+30+day;
System.out.println("这是"+year+"的第"+ri+"天");
break;
case 7:
ri=31+tian+30+31+30+31+day;
System.out.println("这是"+year+"的第"+ri+"天");
break;
case 8:
ri=31+tian+30+31+30+31+31+day;
System.out.println("这是"+year+"的第"+ri+"天");
break;
case 9:
ri=31+tian+30+31+30+31+31+30+day;
System.out.println("这是"+year+"的第"+ri+"天");
break;
case 10:
ri=31+tian+30+31+30+31+31+30+31+day;
System.out.println("这是"+year+"的第"+ri+"天");
break;
case 11:
ri=31+tian+30+31+30+31+31+30+31+30+day;
System.out.println("这是"+year+"的第"+ri+"天");
break;
case 12:
ri=31+tian+30+31+30+31+31+30+31+30+31+day;
System.out.println("这是"+year+"的第"+ri+"天");
break;
}
}
}
代码冗余过高
需要注意闰年平年。
if(month>12&&month<1) {
System.out.println(“非法输入”);
}
if(month==2&&day>30) {
System.out.println(“非法输入”);
}
month–;//如果是一月份则不自增;
switch(month) {
case 12:
case 11:
day+=30;
case 10:
day+=31;
case 9:
day+=30;
case 8:
day+=31;
case 7:
day+=31;
case 6:
day+=30;
case 5:
day+=31;
case 4:
day+=30;
case 3:
day+=31;
case 2:
if((year%4==0&&year%100!=0)||year%400==0) {
day+=29;
}else {
day+=28;
}
case 1:
day+=31;
break;
}
System.out.println(“这是”+year+”年的”+day+”天”);