2009年4月27日 星期一

Class definition 3

Do Display 4.7 (3rd, 2nd ed.) or 4.5 (1st ed.). Then use Display 4.8 to call 4.7.

Question
In Display 4.7, if the method setDate has the parameter as setDate(int month, int day, int year), what kind of changes should be made in its body of codes?


class程式碼
------------------------------------------------<程式碼開始>--------------------------------------
import java.util.Scanner;
public class DateFourthTry {
private int month;
private int day;
private int year;
public void setDate(int month, int day, int year) {
this.month = month;
this.day = day;
this.year = year;
}
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) );
}
}
------------------------------------------------<程式碼結束>--------------------------------------
主程式碼
------------------------------------------------<程式碼開始>--------------------------------------
import java.util.*;
public class Classdefinition3 {
    public static void main (String args[]) {
        DateFourthTry date1 = new DateFourthTry(), date2 = new DateFourthTry();
date1.setDate(6, 17, 1882);
date2.setDate(6, 17, 1882);
if(date1.equals(date2))
System.out.println(date1 + " equals " + date2);
else
System.out.print(date1 + " does not equals " + date2);
date1.setDate(7, 28, 1750);
if(date1.precedes(date2))
System.out.println(date1 + " comes before " + date2);
else
System.out.print(date2 + " comes before or is equal to " + date1);
    }
}
------------------------------------------------<程式碼結束>--------------------------------------
附註:

沒有留言:

張貼留言