objects…get oriented! Making code make sense - fields, initializing objects
Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 3(objects…get oriented! Making code make sense)、p.149(Exercise)の解答を求めてみる。
コード
using System;
namespace MyFirstConsoleApp
{
class Program
{
static void Main(string[] args)
{
Guy joe = new Guy() { Name = "Joe", Cash = 50 };
Guy bob = new Guy() { Name = "Bob", Cash = 100 };
while (true)
{
Console.Write("Enter an amount: ");
string howMuch = Console.ReadLine();
if (howMuch == "")
{
return;
}
if (int.TryParse(howMuch, out int amount))
{
Console.Write("Who should give the cash: ");
string whichGuy = Console.ReadLine();
if (whichGuy == "Joe")
{
bob.ReceiveCash(joe.GiveCash(amount));
}
else if (whichGuy == "Bob")
{
joe.ReceiveCash(bob.GiveCash(amount));
}
else
{
Console.WriteLine("Please enter 'Joe' or 'Bob'");
}
}
else
{
Console.WriteLine("Please enter an amount (or a blank line to exit).");
}
}
}
}
}
入出力結果(Terminal)
Enter an amount: 10
Who should give the cash: Joe
Enter an amount: 20
Who should give the cash: Bob
Enter an amount: 100
Who should give the cash: Bob
Bob says: I don't have enough cash to give you 100
Joe says: 0 isn't an amount Ill take
Enter an amount: 100
Who should give the cash: Joe
Joe says: I don't have enough cash to give you 100
Bob says: 0 isn't an amount Ill take
Enter an amount: abcde
Please enter an amount (or a blank line to exit).
Enter an amount: 10
Who should give the cash: Bobb
Please enter 'Joe' or 'Bob'
Enter an amount: 10
Who should give the cash: Bob
Enter an amount: