07.输入日期判断天数

该博客介绍了一道编程题目,要求输入年、月、日,计算出这一天在当年中的第几天。示例代码给出了解决方案,并展示了运行结果。

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

编程题目:

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

示例代码:

package program.calculation.exercise07;

import java.util.Scanner;

/**
* 7.输入某年某月某日,判断这一天是这一年的第几天?
* 概念:
* 闰年:1.能被4整除而不能被100整除;(如2004年就是闰年,1800年不是。)
* 	  2.能被400整除。(如2000年是闰年。)
* 闰年二月份29天,而平年二月份28天。
* 分析:以4月4日为例,应该先把前三个月的加起来,然后再加上4天即本年的第几天,
*     特殊情况,闰年且输入月份大于3时需考虑多加一天。
*/

public class DayJudge {
	public static void main(String[] args) {
		
		System.out.println("请输入某年某月某日,以空格区分:");
		@SuppressWarnings("resource")
		Scanner scanner = new Scanner(System.in);
		int year = scanner.nextInt();
		int month = scanner.nextInt();
		int day = scanner.nextInt();
		System.out.println("输入的日期为:"+year+"年"+month+"月"+day+"日");
		System.out.println("该日期是一年的第"+calculateDays(year, month, day)+"天");
		
	}
	
	//计算天数
	private static int calculateDays(int year, int month, int day) {
		
	    int days = 0;
		int[] months = null;
		int[] month1 = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};//平年月份天数
		int[] month2 = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};//闰年月份天数
		
		if((0 == year%400)||(0 == year%4 && 0 != year%100)) { //判断是否是平年还是闰年
			months = month2;
		}else {
			months = month1;
		}
		
		if(12<month || 1>month){ //判断输入月份是否合法
			System.out.print("输入月份为非法月份!");
			System.exit(-1); //退出程序
		}
		
		//判断输入月份天数是否合法
		if((months[0]<day||months[2]<day||months[4]<day||months[6]<day
				||months[7]<day||months[9]<day||months[11]<day)
				&& (month==1||month==3||month==5||month==7||month==8||month==10||month==12)) { 
			System.out.print("输入日期为非法日期,此月份最多有"+months[0]+"天!");
			System.exit(-1);
		}
		if((day>months[3]||day>months[5]||day>months[8]||day>months[10])
				&& (month==4||month==6||month==9||month==11)){
			System.out.println("输入非法日期,该月份最多有"+months[3]+"天!");
			System.exit(-1);
		}
		if(months[1]<day) { 
			System.out.print("输入日期为非法日期,此月份最多有"+months[1]+"天!");
			System.exit(-1);
		}
 
		for (int i=0; i<month-1; i++) { //将前几个月份天数相加
			days += months[i];
		}
		return days+day; //再加上本月天数返回
		
	}

}

结果显示:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值