2012年7月19日木曜日

開発環境

『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-294-7)の 第10章(配列)10.9(練習問題)、練習10-4を解いてみる。

練習10-4.

コード

using System;
using System.Text.RegularExpressions;

namespace Sample
{
    class Tester
    {
        public void Run()
        {
            const int rows = 8;
            const int cols = 8;
            string[,] chessboard = new string[rows, cols];
            for (int i = 0; i < rows; i++)
            {
                if (i % 2 == 0)
                {
                    for (int j = 0; j < cols; j++)
                    {
                        chessboard[i, j] = j % 2 == 0 ? "黒" : "白";
                    }
                }
                else
                {
                    for (int j = 0; j < cols; j++)
                    {
                        chessboard[i, j] = j % 2 == 0 ? "白" : "黒";
                    }
                }
            }
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    Console.Write(chessboard[i, j]);
                }
                Console.WriteLine();
            }
            string row = "";
            string col = "";
            Regex reg = new Regex("[1-8]");
            while (true)
            {
                Console.WriteLine("正方形の座標(8×8)を入力");
                while (true)
                {
                    row = Console.ReadLine();
                    if (reg.IsMatch(row))
                    {
                        break;
                    }
                    else
                    {
                        Console.WriteLine("1から8の整数を入力してください");
                        continue;
                    }
                }
                while (true)
                {
                    col = Console.ReadLine();
                    if (reg.IsMatch(col))
                    {
                        break;
                    }
                    else
                    {
                        Console.WriteLine("1から8の整数を入力してください");
                        continue;
                    }
                }
                int m = Convert.ToInt16(row);
                int n = Convert.ToInt16(col);
                Console.WriteLine(chessboard[m - 1, n - 1]);
                Console.Write("続けるかどうか(y/n)");
                string yn = Console.ReadLine();
                if (yn == "n")
                {
                    break;
                }
            }
        }
        static void Main()
        {
            Tester t = new Tester();
            t.Run();
        }
    }
}

入出力結果(Console Window)

黒白黒白黒白黒白
白黒白黒白黒白黒
黒白黒白黒白黒白
白黒白黒白黒白黒
黒白黒白黒白黒白
白黒白黒白黒白黒
黒白黒白黒白黒白
白黒白黒白黒白黒
正方形の座標(8×8)を入力
a
1から8の整数を入力してください
1
1
黒
続けるかどうか(y/n)y
正方形の座標(8×8)を入力
1
2
白
続けるかどうか(y/n)y
正方形の座標(8×8)を入力
5
6
白
続けるかどうか(y/n)y
正方形の座標(8×8)を入力
8
8
黒
続けるかどうか(y/n)n
続行するには何かキーを押してください . . .

0 コメント:

コメントを投稿