2005/12/05

Lab 12-5-2005 (1) Using "this"

Lab 12-5-2005 (1) Using "this"

public class Display
{

private String month;
private int day;
private int year;
public String toString()
{
return (month + " " + day + ", " + year);
}

public void writeOutput()
{
System.out.println(month + " " + day + ", " + year);
}

public boolean equals(Display otherDate)
{
return ( this.month.equals(otherDate.month) && this.day==(otherDate.day) && this.year==(otherDate.year) );
}

public boolean precedes(Display otherDate)
{
return (year < year="=">
(year==otherDate.year && month.equals(otherDate.month) && day <>
}

public int getMonth()
{
if (month.equals("Jan"))
{ return 1; }
else if (month.equals("Feb"))
{ return 2; }
else if (month.equals("Mar"))
{ return 3; }
else if (month.equals("Apr"))
{ return 4; }
else if (month.equals("May"))
{ return 5; }
else if (month.equals("Jun"))
{ return 6; }
else if (month.equals("Jul"))
{ return 7; }
else if (month.equals("Aug"))
{ return 8; }
else if (month.equals("Sep"))
{ return 9; }
else if (month.equals("Oct"))
{ return 10; }
else if (month.equals("Nov"))
{ return 11; }
else if (month.equals("Dec"))
{ return 12; }
else
{
System.out.println("Error");
System.exit(0);
return 0;
}
}

public String monthString(int month_num)
{
switch (month_num)
{
case 1:
return "Jan";
case 2:
return "Feb";
case 3:
return "Mar";
case 4:
return "Apr";
case 5:
return "May";
case 6:
return "Jun";
case 7:
return "Jul";
case 8:
return "Aug";
case 9:
return "Sep";
case 10:
return "Oct";
case 11:
return "Nov";
case 12:
return "Dec";
default:
System.out.println("Error");
System.exit(0);
return "Error";
}
}

public void setDate(int month, int day, int year)
{
this.month = monthString(month);
this.day = day;
this.year = year;
}

}

public class EqualAndToStringDemo {
public static void main(String[] args)
{
Display date1 = new Display();
Display date2 = new Display();
date1.setDate(6, 17, 1882);
date2.setDate(6, 17, 1882);
if (date1.equals(date2))
{ System.out.println(date1 + " equals " + date2); }
else
{ System.out.println(date1 + " does not equal " + date2); }
date1.setDate(7, 28, 1883);

if (date1.precedes(date2))
{ System.out.println(date1 + " comes before " + date2); }
else
{ System.out.println(date2 + " comes after or is equal to " + date1); }

}

}

0 Comments:

張貼留言

<< Home