namespaces and classes - Organizing your code - There’s an easier way to initialize objects with C#
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 3(namespaces and classes - Organizing your code)、p.181(Exercise)の解答を求めてみる。
コード
Guy.cs
namespace Guys;
internal class Guy
{
public string? Name;
public int Cash;
public void WriteMyInfo()
{
Console.WriteLine($"{Name} has {Cash} bucks.");
}
public int GiveCash(int amount)
{
if (amount <= 0)
{
Console.WriteLine($"{Name} says: {amount} isn't a valid amount");
return 0;
}
if (amount > Cash)
{
Console.WriteLine($"{Name} says: I don't have enough cash to give you {amount}");
return 0;
}
Cash -= amount;
return amount;
}
public void ReceiveCash(int amount)
{
if (amount <= 0)
{
Console.WriteLine($"{Name} says: {amount} isn't an amount I'll take");
}
else
{
Cash += amount;
}
}
}
Program.cs
using Guys;
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("Plaese enter 'Joe' or 'Bob'");
}
}
else
{
Console.WriteLine("Please enter an amount (or a blank line to exit).");
}
}
入出力結果(Terminal, Zsh)
Enter an amount: 10
Who should give the cash: Joe
Enter an amount: 40
Who should give the cash: Joe
Enter an amount: 1
Who should give the cash: Joe
Joe says: I don't have enough cash to give you 1
Bob says: 0 isn't an amount I'll take
Enter an amount: 150
Who should give the cash: Bob
Enter an amount: 1
Who should give the cash: bob
Plaese enter 'Joe' or 'Bob'
Enter an amount: Bob
Please enter an amount (or a blank line to exit).
Enter an amount: 1
Who should give the cash: Bob
Bob says: I don't have enough cash to give you 1
Joe says: 0 isn't an amount I'll take
Enter an amount: -1
Who should give the cash: Joe
Joe says: -1 isn't a valid amount
Bob says: 0 isn't an amount I'll take
Enter an amount: