2009年5月4日 星期一

Lab Method Overloading

依據Class definition 3,修改程式使其接受三種setDate

date1.setDate(1,2,2008);
date2.setDate("February",2, 2008);
date3.setDate(2008);



class程式碼
------------------------------------------------<程式碼開始>--------------------------------------
import java.util.*;
public class MethodOverloading {
    public static void main (String args[]) {
DateFourthTry date1 = new DateFourthTry();
DateFourthTry date2 = new DateFourthTry(); 
DateFourthTry date3 = new DateFourthTry();
date1.setDate(1,2,2008);
date2.setDate("February",2, 2008);
date3.setDate(2008);
System.out.println(date1);
System.out.println(date2);
System.out.println(date3);
}
}
------------------------------------------------<程式碼結束>--------------------------------------
主程式碼
------------------------------------------------<程式碼開始>--------------------------------------
import java.util.Scanner;
public class DateFourthTry {
private int month, day, year;
public void setDate(int month, int day, int year) {
this.month = month;
this.day = day;
this.year = year;
}
public void setDate(String stringmonth, int day, int year){
this.month = monthString(stringmonth);
this.day = day;
this.year = year;
}
public void setDate(int year) {
setDate(1, 1, year);
}
public int monthString(String month){
if(month == "January")
return 1;
else if(month == "February")
return 2;
else if(month == "March")
return 3;
else if(month == "April")
return 4;
else if(month == "May")
return 5;
else if(month == "June")
return 6;
else if(month == "July")
return 7;
else if(month == "August")
return 8;
else if(month == "September")
return 9;
else if(month == "October")
return 10;
else if(month == "November")
return 11;
else if(month == "December")
return 12;
else {
System.out.println("Fatal Error");
System.exit(0);
return 0;
}
}
public String toString() {
return (month + " " + day + ", " + year);
}
public int getDay() {
return day;
}
public int getYear() {
return year;
}
public int getMonth() {
return month;
}
public boolean equals(DateFourthTry otherDate) {
return( (month == otherDate.month) && (day == otherDate.day) && (year == otherDate.year) );
}
public boolean precedes(DateFourthTry otherDate) {
return ( (year < otherDate.year) || 
(year == otherDate.year && getMonth() < otherDate.getMonth() ) || 
(year == otherDate.year && month == otherDate.month && day < otherDate.day) );
}
}
------------------------------------------------<程式碼結束>--------------------------------------
附註:

沒有留言:

張貼留言