計算機科学のブログ

encapsulation - Keep your privates… private - properties, constructor

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 5(encapsulation - Keep your privates… private)、p.261(Pool Puzzle)の解答を求めてみる。

コード

Q.cs

using System;
namespace MyFirstConsoleApp
{
    public class Q
    {
        public Q(bool add)
        {
            if (add)
            {
                Op = "+";
            }
            else
            {
                Op = "*";
            }
            N1 = R.Next(1, 10);
            N2 = R.Next(1, 10);
        }
        public static Random R = new Random();
        public int N1 { get; private set; }
        public string Op { get; private set; }
        public int N2 { get; private set; }

        public bool Check(int a)
        {
            if (Op == "+")
            {
                return a == N1 + N2;
            }
            return a == N1 * N2;
        }
    }
}

コード

Program.cs

using System;

namespace MyFirstConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Q q = new Q(Q.R.Next(2) == 1);
            while (true)
            {
                Console.Write($"{q.N1} {q.Op} {q.N2} = ");
                if (!int.TryParse(Console.ReadLine(), out int i))
                {
                    Console.WriteLine("Thanks for playing!");
                    return;
                }
                if (q.Check(i))
                {
                    Console.WriteLine("Right!");
                    q = new Q(Q.R.Next(2) == 1);
                }
                else
                {
                    Console.WriteLine("Wrong! Try agin.");
                }
            }
        }
    }
}

入出力結果(Terminal, Zsh)

4 + 8 = 12
Right!
4 + 9 = 13
Right!
8 * 4 = 32
Right!
4 * 2 = 8
Right!
1 + 6 = 7
Right!
3 * 9 = 1
Wrong! Try agin.
3 * 9 = 2
Wrong! Try agin.
3 * 9 = 27
Right!
9 * 7 = 1
Wrong! Try agin.
9 * 7 = 63
Right!
3 + 3 = Bye
Thanks for playing!