import java.util.Scanner;
public class SmartDate {
private final int month;
private final int day;
private final int year;
public SmartDate(int m, int d, int y) {
switch (m) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (d > 0 && d <= 31) {
month = m;
day = d;
year = y;
} else {
throw new IllegalArgumentException("Illegal date");
}
break;
case 4:
case 6:
case 9:
case 11:
if (d > 0 && d <= 30) {
month = m;
day = d;
year = y;
} else {
throw new IllegalArgumentException("Illegal date");
}
break;
case 2:
if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) {
if (d > 0 && d <= 29) {
month = m;
day = d;
year = y;
} else {
throw new IllegalArgumentException("Illegal date");
}
} else {
if (d > 0 && d <= 28) {
month = m;
day = d;
year = y;
} else {
throw new IllegalArgumentException("Illegal date");
}
}
break;
default:
throw new IllegalArgumentException("Illegal date");
}
}
public int month() {
return month;
}
public int day() {
return day;
}
public int year() {
return year;
}
/**
* Exercise 1.2.12
*
* @return day of the week
*/
public String dayOfTheWeek() {
// Zeller formula
int month = this.month;
int year = this.year;
if (month <= 2) {
month += 12;
year--;
}
int week = (day + 2 * month + 3 * (month + 1) / 5 + year + year / 4 - year / 100 + year / 400) % 7;
switch (week) {
case 0:
return "Monday";
case 1:
return "Tuesday";
case 2:
return "Wednesday";
case 3:
return "Thursday";
case 4:
return "Friday";
case 5:
return "Saturday";
case 6:
return "Sunday";
default:
return null;
}
}
public String toString() {
return month() + "/" + day() + "/" + year();
}
/*
public boolean equals(Object x) {
if (this == x) {
return true;
}
if (x == null) {
return false;
}
if (this.getClass() != x.getClass()) {
return false;
}
SmartDate that = (SmartDate) x;
if (this.day != that.day) {
return false;
}
if (this.month != that.month) {
return false;
}
if (this.year != that.year) {
return false;
}
return true;
}//这段代码的作用是什么?*/
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int m = sc.nextInt();
int d = sc.nextInt();
int y = sc.nextInt();
try {
SmartDate date = new SmartDate(m, d, y);
System.out.println(date);//??
System.out.println(date.dayOfTheWeek());//??
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
不太清楚你具体问的是那一段代码,如果是dayOfTheWeek这个方法体中的,这里就是在通过一段自己设定的算法,通过获取到的天,月等时间计算出当天是星期几。具体的计算方式,就要思考一下了,
你的问题描述的不够清晰
我也是刚刚开始学java的,以我的理解上面的那段代码是重写了equals()方法,因为原先的equals()方法是比较两个对象的引用是否相同,而通过上面那段代码,调用equals()方法时就变成比较两个对象的值是否相同。我也刚刚开始学习,如有不对的,还望大神指点!
跑了一下你的代码,这个方法对你的逻辑上并没有太大的影响,然后你可以点进去看看,他是重写了equals()方法,楼下朋友的回答正解
那段就是用来判定两个日期是否相同的! 相同返回true,不同返回false。你再创建一个SmartDate的实例,调用一下这个函数和原来的比一下就明白了!