mysql 一年中的第几天_计算某个日期是一年中的第几天

public static void main(String[] args) {

System.out.println("接收用户输入一个月份和一个日期,计算出是一年当中的第几天");

System.out.println("\t输入月份后,按下回车,在输入日期");

System.out.println("\n请输入4位年数字");

while (true) {

int x;

int day = 0;

int cal = 0;

Scanner scanner = new Scanner(System.in);

int year = scanner.nextInt();

boolean leapYear = isLeapYear(year);

System.out.println("请输入月份:");

int month = scanner.nextInt();

// 闰年2月29天

if (month == 2 && leapYear) {

System.out.println("请输入日期:");

day = scanner.nextInt();

while (day > 29 || day < 1) {

System.out.println("输入有误,重新输入日期:");

x = scanner.nextInt();

day = x;

}

}

// 平年2月28天

if (month == 2 && !leapYear) {

System.out.println("请输入日期:");

day = scanner.nextInt();

while (day > 28 || day < 1) {

System.out.println("输入有误,重新输入日期:");

x = scanner.nextInt();

day = x;

}

}

if (month % 2 != 0) {

System.out.println("请输入日期:");

day = scanner.nextInt();

while (day > 31 || day < 1) {

System.out.println("输入有误,重新输入日期:");

x = scanner.nextInt();

day = x;

}

}

if (month != 2 && month % 2 == 0) {

System.out.println("请输入日期:");

day = scanner.nextInt();

while (day > 30 || day < 1) {

System.out.println("输入有误,重新输入日期:");

x = scanner.nextInt();

day = x;

}

}

System.out.println("你输入的是:" + year + "年" + month + "月" + day + "日");

cal = getDays(year, month, day);

System.out.println(year + "年" + month + "月" + day + "日, 是" + year + "中第" + cal + "天");

}

}

/**

* 判断是否是闰年

* 能被4整除且不能被100整除,或者 能被400整除

* @param year

* @return

*/

public static boolean isLeapYear(int year) {

boolean leapYear = false;

if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {

leapYear = true;

}

return leapYear;

}

/**

* 根据年,月,日,计算总天数

* @param year

* @param month

* @return

*/

public static int getDays(int year, int month, int day) {

int arr[] = {31, 28, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30};

boolean leapYear = isLeapYear(year);

if (leapYear) {

arr[1] = 29;

}

int sum = 0;

for (int i = 0; i < month -1; i++) {

sum += arr[i];

}

sum = sum + day;

return sum;

}

代码逻辑:

(1)判断输入的年份是否是闰年,判断标准:能被4整除且不能被100整除 或者 能被400整除

(2)月份检查,分为4中情况

a.闰年且为2月,此时2月有29天

b.平年且为2月,此时2月有28天

c.平年,能被2整除,此时月份有30天

d.平年,不能被2整除,此时月份有31天

(3)计算天数,初始化一个平年的月份天数数组,如果为闰年,则更改数组中2月的天数,循环累加天数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值