namespaces and classes - Organizing your code - Console App, Write, ReadLine, int, TryParse, if/else statement
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.143(Exercise)の解答を求めてみる。
コード
Program.cs
namespace PickRandomCards;
class Program
{
static void Main(string[] args)
{
Console.Write("Enter the number of cards to pick: ");
string? line = Console.ReadLine();
if (int.TryParse(line, out int numberOfCards))
{
foreach (string card in CardPicker.PickSomeCards(numberOfCards))
{
Console.WriteLine(card);
}
}
else
{
Console.WriteLine($"Invalid input '{line}'");
}
}
}
入出力結果(Terminal, Zsh)
Enter the number of cards to pick: 5
3 of Hearts
10 of Spades
King of Spades
9 of Hearts
6 of Diamonds
Enter the number of cards to pick: 10
7 of Diamonds
King of Hearts
3 of Diamonds
4 of Diamonds
Queen of Hearts
4 of Clubs
Jack of Spades
Ace of Clubs
5 of Diamonds
8 of Hearts
Enter the number of cards to pick: cards
Invalid input 'cards'