题目
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;
}
}
}
运行结果
说明
个人能力有限,仅供参考,共同学习!