计蒜客——恋爱纪念日(学习如何格式化打印日期)

题目要求

输入格式:

  • 输入4个整数y, m, d,k,表示他们在一起的日期,保证是一个1900年1月1日以后的日期, 蒜头君想知道他们的k(0<=k<=10000)天纪念日。

输出格式:

  • 输出格式按照yyyy-mm-dd的格式输出k天纪念日的日期。月份和天数必须各输出2位。 保证最后答案年份不超过4位。

学了Date之后,知道为什么题目说是1900之后的日期了

代码:

  1. 用数组将每个月的最大天数存起来,就不用写switch语句了
  2. 要知道纪念日在什么时候,就是求年-月-日
  3. 对于边界的情况的考虑:如果输入的day已经在一个月的最后一天了,那么day++,就会超过合法范围,需要将day更新为1.
public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int year = scanner.nextInt();
		int month = scanner.nextInt();
		int day = scanner.nextInt();
		int k = scanner.nextInt();
		int[] days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		for (int i = 1; i <= k; i++) {
			// 判断闰年
			if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
				days[2] = 29;
			}
			day++;// 循环遍历找k天后的纪念日
			if (day == days[month] + 1) {
				day = 1;
				month++;
			}
			if (month == 13) {
				year++;
				month = 1;
			}
		}
		System.out.printf("%4d-%02d-%02d", year, month, day);
	}

//用Date()来打印日期

		Date date = new Date();
		// 输出当前的日期
		System.out.printf("%tF", date);
		// 输出指定的日期
		date.setYear(year - 1900);// set(year)中的year=year+1900,所以必须减下来
		date.setMonth(month - 1);// 我不知道为什么就只有month的范围是[0,11]
		date.setDate(day);
		System.out.println();
		System.out.printf("%tF", date);

end.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值