2. 定义一个满足如下要求的Date类: ① 用下面的格式输出日期:日/月/年 ② 可运行在日期上加一天操作; ③ 设置日期;

题目

‬‬2. 定义一个满足如下要求的Date类:
① 用下面的格式输出日期:日/月/年
② 可运行在日期上加一天操作;
③ 设置日期;

参考代码

‘TestMain’ 类

public class TestMain {
	public static void main(String[] args) {
		Date date = new Date();
		System.out.print("初始");
		date.showDate();
		//设置日期
		date.setDate();
		//日期加一天
		date.datePlus();
	}
}

‘Date’ 类

import java.util.Scanner;

public class Date {
	private int year,month,day;
	private int[] mon = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
	public Date() {
		this.year = 0;
		this.month = 1;
		this.day = 1;
	}

	public Date(int year, int month, int day) {
		super();
		this.year = year;
		this.month = month;
		this.day = day;
	}
	
	public void showDate() {
		System.out.println("日期:" + this.day + "日" + this.month + "月" + this.year + "年");
	}
	
	public void setDate() {
		Scanner scanner = new Scanner(System.in);
		System.out.print("请输入年:");
		this.year = scanner.nextInt();
		this.judgeYear();
		System.out.print("请输入月:");
		this.month = scanner.nextInt();
		System.out.print("请输入日:");
		this.day = scanner.nextInt();
		scanner.close();
		System.err.print("设置后");
		this.showDate();
	}
	
	public void datePlus() {
		if (this.mon[this.month-1] > this.day) {
			this.day++;
		}else if (this.month < 12 && this.mon[this.month-1] == this.day) {
			this.month++;
			this.day=1;
		}else if (this.month == 12 && this.mon[this.month-1] == this.day) {
			this.year++;
			this.judgeYear();
			this.month=1;
			this.day=1;
		}
		System.out.print("加上一天的");
		this.showDate();
	}
	
	public void judgeYear() {
		if (this.year % 4 ==0 && this.year % 100 != 0 || this.year % 400 == 0) {
			this.mon[1] = 29;
		}else {
			this.mon[1] = 28;
		}
	}
}

运行结果

在这里插入图片描述

说明

个人能力有限,仅供参考,共同学习!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

无奈清风吹过

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值