2017年12月21日木曜日

開発環境

初めてのC# 第2版 (Jesse Liberty (著)、Brian MacDonald (著)日向 俊二 (翻訳)、オライリージャパン)の10章(配列)、10.9(練習問題)、問題10-3.を取り組んでみる。

コード

using System;

namespace Sample10
{
    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;
            }
            set
            {
                weight = value;
            }
        }
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Dog milo = new Dog(26, "Milo");
            Dog frisky = new Dog(10, "Frisky");
            Dog laika = new Dog(50, "Laika");

            Dog[] dogs = { milo, frisky, laika };
            string[][] dogPrizes = new string[dogs.Length][];

            dogPrizes[0] = new string[2] { "prize1", "prize2" };
            dogPrizes[1] = new string[1] { "prize3" };
            dogPrizes[2] = new string[0] { };

            for (int i = 0; i < dogs.Length; i++)
            {
                Console.Write("Name: {0}, Weight: {1}, Prizes:",
                              dogs[i].Name, dogs[i].Weight);

                bool b = true;
                foreach (var prize in dogPrizes[i])
                {
                    if (b)
                    {
                        Console.Write(" ");
                        b = false;
                    }
                    else
                    {
                        Console.Write(", ");
                    }
                    Console.Write("{0}", prize);
                }
                Console.WriteLine();
            }
        }
    }
}

入出力結果(Terminal)

Name: Milo, Weight: 26, Prizes: prize1, prize2
Name: Frisky, Weight: 10, Prizes: prize3
Name: Laika, Weight: 50, Prizes:

Press any key to continue...

0 コメント:

コメントを投稿