開発環境
- Microsoft Windows 8 Pro 64bit 日本語 (OS)
- Microsoft Visual Studio Express 2012 for Windows Desktop (IDE)
- プログラミング言語: C#
『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487312-194-7)の 第10章(配列)8.5(練習問題)練習10-3.を解いてみる。
その他参考書籍
練習10-3.
コード
using System;
class Dog
{
private int weight;
private string name;
public Dog(int weight, string name)
{
this.weight = weight;
this.name = name;
}
public int Weight
{
get { return weight; }
}
public string Name
{
get { return name; }
}
}
class Tester
{
public void Run()
{
Dog milo = new Dog(26, "Milo");
Dog frisky = new Dog(10, "Frisky");
Dog laika = new Dog(50, "Laika");
Dog[] dogs = { milo, frisky, laika };
string[][] awards = new string[dogs.Length][];
awards[0] = new string[3];
awards[1] = new string[1];
awards[2] = new string[2];
awards[0][0] = "award1";
awards[0][1] = "award2";
awards[0][2] = "award3";
awards[1][0] = "award4";
awards[2][0] = "award5";
awards[2][1] = "award6";
for (int i = 0; i < dogs.Length; i++)
{
Console.WriteLine("{0}: {1}", dogs[i].Name, dogs[i].Weight);
foreach (string award in awards[i])
{
Console.Write("{0} ", award);
}
Console.WriteLine();
}
}
static void Main()
{
Tester t = new Tester();
t.Run();
}
}
入出力結果(Console Window)
Milo: 26 award1 award2 award3 Frisky: 10 award4 Laika: 50 award5 award6 続行するには何かキーを押してください . . .
ちなみにJavaScriptの場合。
コード(BBEdit)
var Dog = function( weight, name ) {
var weight = weight,
name = name;
this.getWeight = function ( ) {
return weight;
};
this.getName = function( ) {
return name;
};
},
milo = new Dog(26, "Milo"),
frisky = new Dog(10, "Frisky"),
laika = new Dog(50, "Laika"),
result = "",
dogs = [milo, frisky, laika],
awards = {
"Milo": ["award1", "award2", "award3"],
"Frisky": ["award4"],
"Laika": ["award5", "award6"]
},
result = "",
i, max;
for (i = 0, max = dogs.length; i < max; i += 1) {
result += dogs[i].getName() + ": " + dogs[i].getWeight() + "\n" +
awards[dogs[i].getName()].join(" ") + "\n";
}
$('#pre0').text(result);
pythonの場合。
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
class Dog:
def __init__(self, weight, name):
self._weight = weight
self._name = name
def getName(self):
return self._name
def getWeight(self):
return self._weight
milo = Dog(26, "Milo")
frisky = Dog(10, "Frisky")
laika = Dog(50, "Laika")
dogs = [milo, frisky, laika]
awards = {milo:["award1", "award2", "award3"], frisky: ["awards4"],
laika: ["award5", "award6"]}
for dog in dogs:
print("{0}: {1}".format(dog.getName(), dog.getWeight()))
print(" ".join(awards[dog]))
入出力結果(Terminal)
$ ./sample.py Milo: 26 award1 award2 award3 Frisky: 10 awards4 Laika: 50 award5 award6 $
0 コメント:
コメントを投稿