java--输入某年某月某日,判断这一天是这一年的第几天?

本文介绍了一种计算给定日期(包括年、月、日)为该年中第几天的方法,提供了两种Java实现方案,分别通过switch-case语句和数组累加的方式进行计算,同时考虑了闰年对二月天数的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于3时需考虑多加一天。

import java.util.Scanner;

public class test {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		System.out.println("请输入年、月、日:");
		int year = scanner.nextInt();
		int month = scanner.nextInt();
		int day = scanner.nextInt();
		int flag = 0;
		if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
			flag = 1;
		else
			flag = 0;

		switch (month - 1) {
		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:
			day += 28 + flag;
		case 1:
			day += 31;
		case 0:
			day += 0;
			break;
		default:
			System.out.println("请输入正确的月份。");
			break;
		}

		System.out.println("这一天是这一年的第" + day + "天");

	}

}

示例输出:
在这里插入图片描述

另一个方法:

import java.util.Scanner;

public class test {

	public static void main(String[] args){
		Scanner scan = new Scanner(System.in);
		System.out.print("请输入当前日期(年-月-日):");
		int year = scan.nextInt();
		int month = scan.nextInt();
		int date = scan.nextInt();
		scan.close();
		System.out.println("今天是"+year+"年的第"+analysis(year,month,date)+"天");
	}
	//判断天数
	private static int analysis(int year, int month, int date){
		int n = 0;
		int[] month_date = new int[] {0,31,28,31,30,31,30,31,31,30,31,30};
		if((year%400)==0 || ((year%4)==0)&&((year%100)!=0))
		  month_date[2] = 29;
		for(int i=0;i<month;i++)
		  n += month_date[i];
		return n+date;
	}
}

输出:
在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

~祝今在

喝个茶水

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值