内容简介
使用 if 和 swtich 选择结构实现判断输入的某年某月某日是这一年的第几天 ,其中分辨出是闰年还是平年 Switch 主要是判断是哪个月份的 if语句中主要判断是否为闰年。
代码展示
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入年份");
int year=sc.nextInt();
System.out.println("输入月份");
int month=sc.nextInt();
System.out.println("输入日期");
int day=sc.nextInt();
int flat=0;
if(year % 4 == 0 && year % 100 != 0||year%400==0) //判断是否是闰年
//是的话 flat 为1 标记
flat=1;
switch(month){
case 1:
System.out.println(day);
break;
case 2:
day=day+31;
System.out.println(day);
break;
case 3:
if(flat==1)
day=day+60;
else
day=day+59;
System.out.println(day);
break;
case 4:
if(flat==1)
day=day+91;
else
day=day+90;
System.out.println(day);
break;
case 5:
if(flat==1)
day=day+121;
else
day=day+120;
System.out.println(day);
break;
case 6:
if(flat==1)
day=day+152;
else
day=day+151;
System.out.println(day);
break;
case 7:
if(flat==1)
day=day+182;
else
day=day+181;
System.out.println(day);
break;
case 8:
if(flat==1)
day=day+213;
else
day=day+212;
System.out.println(day);
break;
case 9:
if(flat==1)
day=day+244;
else
day=day+243;
System.out.println(day);
break;
case 10:
if(flat==1)
day=day+274;
else
day=day+273;
System.out.println(day);
break;
case 11:
if(flat==1)
day=day+305;
else
day=day+304;
System.out.println(day);
break;
case 12:
if(flat==1)
day=day+335;
else
day=day+334;
System.out.println(day);
break;
}
}
}
结果
闰年时结果 平年时结果
希望这篇博客对你有所帮助,本人也出初学 java 有很多细节没有处理好,本着记录学习过程写了这篇博客。