objects…get oriented! Making code make sense - while loop, int, TryParse, Console, WriteLine, ReadLine, if/else
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.151(Exercise(Part 2))の解答を求めてみる。
コード
using System;
namespace MyFirstConsoleApp
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
double odds = 0.75;
Guy player = new Guy() { Name = "The player", Cash = 100 };
Console.WriteLine($"Welcom to the casino. The odds are {odds}");
while (player.Cash > 0)
{
player.WriteMyInfo();
Console.Write("How much do you want to bet: ");
string howMuch = Console.ReadLine();
if (int.TryParse(howMuch, out int amount))
{
int pot = player.GiveCash(amount);
pot *= 2;
if (random.NextDouble() > odds)
{
Console.WriteLine($"You win {pot}");
player.ReceiveCash(pot);
}
else
{
Console.WriteLine("Bad luck, you lose.");
}
}
else
{
Console.WriteLine("Invalid input(Not a Int)");
}
}
Console.WriteLine("The house always wins.");
}
}
}
入出力結果(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
Welcom to the casino. The odds are 0.75
The player has 100 bucks.
How much do you want to bet: 36
Bad luck, you lose.
The player has 64 bucks.
How much do you want to bet: 27
Bad luck, you lose.
The player has 37 bucks.
How much do you want to bet: 83
The player says: I don't have enough cash to give you 83
Bad luck, you lose.
The player has 37 bucks.
How much do you want to bet: 8
Bad luck, you lose.
The player has 29 bucks.
How much do you want to bet: a
Invalid input(Not a Int)
The player has 29 bucks.
How much do you want to bet: 29
Bad luck, you lose.
The house always wins.