教育サーバーのページ
オンラインテキスト目次
ソフトウエア入門演習
// VideoTapeクラス内に以下のメソッドを追加 public void foward(int t1, int t2, int t3) { position += t1 + t2 + t3; // あるいは foward(t1 + t2 + t3); } // 以下はmainメソッド public static void main(String[] args) { VideoTape vt = new VideoTape(); vt.forward(10, 20, 15); // ただしget_positionがVideoTapeクラスに定義されていることが前提 System.out.println("position = " + vt.get_position()); }
// VideoTapeクラス内に以下のメソッドを追加 public void foward(int []t) { for (int i = 0; i < t.length; i++) { position += t[i]; // あるいは forward(t[i]); } } // 以下はmainメソッド public static void main(String[] args) { VideoTape vt = new VideoTape(); int[] times = {10, 20, 15}; vt.forward(times); // ただしget_positionがVideoTapeクラスに定義されていることが前提 System.out.println("position = " + vt.get_position()); }
// VideoTapeクラス内に以下のコンストラクタを追加 VideoTape(int h, int m, int s) { position = h*60*60+m*60+s; } // 以下はmainメソッド public static void main(String[] args) { VideoTape vt = new VideoTape(2, 30, 15); // ただしget_positionがVideoTapeクラスに定義されていることが前提 System.out.println("position = " + vt.get_position()); }
class Rectangle { // 長方形クラス public double x1, y1;// 頂点の1つ public double x2, y2;// 頂点の1つ (x1,y2)の対角 public String color; // 長方形の色 public void set(double x, double y, double width, double height) { // 左下の位置と幅と高さを指定 x1 = x; y1 = y; x2 = x+width; y2 = y+height; } } // Squareクラスの定義は変更なし public class RectangleTest { static void main(String[] args) { Square s = new Square(); s.color = "red"; System.out.println("sの色は" + s.color + "です。"); Rectangle r = new Rectangle(); r.color = "blue"; System.out.println("rの色は" + r.color + "です。"); } }
class Crow extends Bird { // カラスのクラス public void fly() { super.fly(); System.out.println("時には人を攻撃 します"); } }
class Dog { public String name; public double weight; public static int number=0; public static double total_weight=0; Dog(double w) { weight = w; total_weight += w; number++; } Dog(double w, String n) { weight = w; total_weight += w; number++; name = n; } } public class DogExample { public static void main(String[] args) { System.out.println("犬の総体重" + Dog.total_weight); Dog pochi = new Dog(20); System.out.println("犬の総体重=" + Dog.total_weight); System.out.println("ポチの体重=" + pochi.weight); Dog shiro = new Dog(18, "シロ"); System.out.println("犬の総体重=" + Dog.total_weight); System.out.println("シロの体重=" + shiro.weight); } }なお、この問題では、total_weightとweightなどをpublicとしているが、 直接値を書き変えられないようにprivateにして、get_weight()、 get_total_weight()といったアクセスメソッドを用意するほうが望ましい。