encapsulation - Keep your privates...private - constructor, arguments, properties
Head First C Sharp: A Learner’s Guide to Real-World Programming with C Sharp and .NET (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)の Chapter 5(encapsulation - Keep your privates…private)、p.261(Pool Puzzle)の解答を求めてみる。
コード
Program.cs
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!");
break;
}
if (q.Check(i))
{
Console.WriteLine($"Right!");
q = new Q(Q.R.Next(2) == 1);
}
else
{
Console.WriteLine("Wrong! Try again.");
}
}
internal 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;
}
}
入出力結果(Terminal, Zsh)
% dotnet run
3 + 3 = 6
Right!
7 * 4 = 28
Right!
7 * 1 = 7
Right!
1 + 4 = 5
Right!
4 * 1 = 4
Right!
1 * 8 = 0
Wrong! Try again.
1 * 8 = a
Thanks for playing!
%