エンジニア成長日記 swaponQ

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

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

Hello, Terminal!swaponQです!

今回から「第9章:日付クラスの作成」に入ります。

第9章は演習が5題ありますが、こちらもじっくり解いていきます。

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

  • 演習 9-1

演習8-1で作成した《人間クラス》の配列を生成するプログラムを作成せよ。生成時に要素を初期化するもの、生成後の要素に値を代入するものなど、複数のパターンを作ること。

・Human.java

public class Human {
  //フィールド
  private String name;
  private int height;
  private int weight;
  //コンストラクタ
  Human(String name, int height, int weight) {
    this.name = name;
    this.height = height;
    this.weight = weight;
  }
  //メソッド
  void putSpec() {
    System.out.printf("名前:%s\n", name);
    System.out.printf("身長:%d cm\n", height);
    System.out.printf("体重:%d kg\n", weight);
  }
}

・ex09_1.java

class ex09_1 {
  public static void main(String[] args) {
    Human[] x = new Human[3];
    for (int i=0; i<x.length; i++) {
      String humanName = "HumanX" + (i + 1);
      x[i] = new Human(humanName, 150, 50);
    }
    for (int i=0; i<x.length; i++) {
      x[i].putSpec();
    }
    System.out.println("-------------");
    Human[] y = {
      new Human("HumanY1", 160, 60),
      new Human("HumanY2", 160, 60),
      new Human("HumanY3", 160, 60)
    };
    for (int i=0; i<y.length; i++) {
      y[i].putSpec();
    }
    System.out.println("-------------");
    Human[] z;
    z = new Human[]{
      new Human("HumanZ1", 170, 70),
      new Human("HumanZ2", 170, 70),
      new Human("HumanZ3", 170, 70)
    };
    for (int i=0; i<z.length; i++) {
      z[i].putSpec();
    }
  }
}

・実行結果

名前:HumanX1
身長:150 cm
体重:50 kg
名前:HumanX2
身長:150 cm
体重:50 kg
名前:HumanX3
身長:150 cm
体重:50 kg
-------------
名前:HumanY1
身長:160 cm
体重:60 kg
名前:HumanY2

身長:160 cm
体重:60 kg
名前:HumanY3
身長:160 cm
体重:60 kg
-------------
名前:HumanZ1
身長:170 cm
体重:70 kg
名前:HumanZ2
身長:170 cm
体重:70 kg
名前:HumanZ3
身長:170 cm
体重:70 kg

今回は以上です。お疲れ様でした!
次回は演習 9-2 です。

Goodbye, Terminal… swaponQでした!