public class Date {
private int m; // month
private int d; // day
private int y; // year
private String month; // string month name ex. "January"
private int day; // int day
private int year;// year
private boolean equals; // make the dates equal
public Date(int m, int d, int y) {
this.m = m;
this.d = d;
this.y = y;
}
public Date(String month, int d, int y) {
this.month = month;
this.d = d;
this.y = y;
}
public boolean equals(Object other) {
if (!(other instanceof Date)) {
return false;
}
Date d2 = (Date) other;
if (y == d2.y) {
if (m == d2.m) {
if (d == d2.d) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
public String toString() {
if (m == 1) {
return "January " + d + ", " + y;
} else if (m == 2) {
return "February " + d + ", " + y;
} else if (m == 3) {
return "March " + d + ", " + y;
} else if (m == 4) {
return "April " + d + ", " + y;
} else if (m == 5) {
return "May " + d + ", " + y;
} else if (m == 6) {
return "June " + d + ", " + y;
} else if (m == 7) {
return "July " + d + ", " + y;
} else if (m == 8) {
return "August " + d + ", " + y;
} else if (m == 9) {
return "Septmember " + d + ", " + y;
} else if (m == 10) {
return "October " + d + ", " + y;
} else if (m == 11) {
return "November " + d + ", " + y;
} else if (m == 12) {
return "December " + d + ", " + y;
} else {
return month + " " + d + ", " + y;
}
}
}
import java.util.Random;
public class DateDemo {
public static void test(Date d1, Date d2) {
if (d1.equals(d2)) {
System.out.println("\"" + d1 + "\" matches \"" + d2 + "\"");
} else {
System.out.println("\"" + d1 + "\" doesn't matche \"" + d2 + "\"");
}
}
public static void main(String[] args) {
test(new Date("January", 1, 1970), new Date(1, 1, 1970));
test(new Date("December", 20, 1970), new Date(12, 20, 1971));
test(new Date("July", 15, 1970), new Date(7, 14, 1970));
test(new Date("July", 15, 1970), new Date(7, 15, 1970));
test(new Date("November", 1, 1970), new Date(11, 1, 1970));
test(new Date("April", 1, 1492), new Date(4, 1, 1492));
test(new Date("March", 1, 1970), new Date(1, 1, 1970));
Date d = new Date("January", 1, 1970);
if (d.equals(new String("Blah"))) {
System.out.println("Should not see me");
} else {
System.out.println("Date can only possibly match another Date");
}
}
}
對不起,這是我的第一篇文章,我需要幫助如何將月份名稱「1月」轉換爲整數「1」,以及如何使日期相等,當我運行它返回,他們不匹配。如何將字符串轉換爲int?
封裝你幾個月的枚舉,那麼你可以利用序方法來獲取相關的整數。 – ferahgo