在尚硅谷学习的第6天,作业有个这个,我查了一下大部分都是用 switch 的好像没我这种的
自己琢磨半天,来这边找点成就感波~
基本思路就是:
确认年份(year)区分平年闰年;
确认月份(month)把当月之前的月份天数加上;
确认天数(day)把当月的天数加上;
因此需要定义一个变量days来存储计算结果并打印。
变量year用来判断平年闰年,变量month用来确定遍历多少次,变量day提前赋给days用作叠加。
代码如下:
public class demo5 {
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();
//闰年1-12月天数: 31,29,31,30,31,30,31,31,30,31,30,31
//平年1-12月天数: 31,28,31,30,31,30,31,31,30,31,30,31
int days = day;
int[] monthArr = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; //闰年
int[] monthBrr = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; //平年
//如果是闰年
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
for (int i = 1; i < month; i++) {
days += monthArr[i];
}
} else { //如果是平年
for (int i = 1; i < month; i++) {
days += monthBrr[i];
}
}
System.out.println("今天是"+year + "年的第:" + days + "天");
}
}