エンジニア成長日記 swaponQ

コンピュータサイエンス専攻の一般人のブログです。

新・明解 Java 入門 演習 9-5 解答

Hello, Terminal!swaponQです!

今回は演習 9-5 に取り組んでいこうと思います。

  • 演習 9-5

開始日と終了日とから構成される《期間》を表すクラスPeriodを作成せよ。コンストラクタやメソッドを自由に定義すること。

・Day.java

// Dayクラス
public class Day {
	private int	year	= 1;		// 年
	private int	month = 1;		// 月
	private int	date 	= 1;		// 日

	//-- コンストラクタ --//
	public Day()                              { }
	public Day(int year)                      { this.year = year; }
	public Day(int year, int month)           { this(year); this.month = month; }
	public Day(int year, int month, int date) { this(year, month); this.date = date; }
	public Day(Day d)                         { this(d.year, d.month, d.date); }

	//--- 年・月・日を取得 ---//
	public int getYear()  { return year; }		// 年を取得
	public int getMonth() { return month; }	// 月を取得
	public int getDate()  { return date; }		// 日を取得

	//--- 年・月・日を設定 ---//
	public void setYear(int year)   { this.year  = year; }	// 年を設定
	public void setMonth(int month) { this.month = month; }	// 月を設定
	public void setDate(int date)   { this.date  = date; }	// 日を設定

	public void set(int year, int month, int date) {			// 年月日を設定
		this.year  = year;			// 年
		this.month = month;			// 月
		this.date  = date;			// 日
	}

	//--- 曜日を求める ---//
	public int dayOfWeek() {
		int y = year;					// 0 … 日曜日
		int m = month;					// 1 … 月曜日
		if (m == 1 || m == 2) {		//  :
			y--;							// 5 … 金曜日
			m += 12;						// 6 … 土曜日
		}
		return (y + y / 4 - y / 100 + y / 400 + (13 * m + 8) / 5 + date) % 7;
	}

	//--- 日付dと等しいか ---//
	public boolean equalTo(Day d) {
		return year == d.year && month == d.month && date == d.date;
	}

	//--- 文字列表現を返却 ---//
	public String toString() {
		String[] wd = {"日", "月", "火", "水", "木", "金", "土"};
		return String.format("%04d年%02d月%02d日(%s)",
										year, month, date, wd[dayOfWeek()]);
	}
}

・Period.java

// Periodクラスを書く
class Period {
  private Day from; //開始日
  private Day to;  //終了日

  public Period(Day from, Day to) {
    this.from = new Day(from);
    this.to = new Day(to);
  }

  public Day getFrom() {
    return new Day(from);
  }

  public Day getTo() {
    return new Day(to);
  }

  public void putSpec() {
    System.out.println("開始日:" + from);
    System.out.println("終了日:" + to);
  }
}

・ex09_5.java

// 期間クラスをテストするクラス
class ex09_5 {
  public static void main(String[] args) {
    Day from = new Day(2000, 1, 1);
    Day to = new Day(2020, 8, 4);
    Period p = new Period(from, to);
    p.putSpec();
  }
}

・実行結果

開始日:2000年01月01日(土)
終了日:2020年08月04日(火)

以上で「第9章:日付クラスの作成」は終了です。お疲れ様でした!
次回からは「第10章:クラス変数とクラスメソッド」です。
これからも頑張りましょう!

Goodbye, Terminal… swaponQでした!