計算機科学のブログ

objects…get oriented! Making code make sense - ReadLine method, Write method, foreach loop

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.111(Exercise)の解答を求めてみる。

コード

using System;
using System.Collections.Generic;

namespace PickRandomCards
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                Console.Write("Enter the nuimber of cards to pick(quit): ");
                string line = Console.ReadLine();
                if (line == "quit")
                {
                    break;
                }
                if (int.TryParse(line, out int numberOfCards))
                {
                    if (numberOfCards > 0)
                    {
                        foreach (string card in CardPicker.PickSomeCards(numberOfCards))
                        {
                            Console.WriteLine(card);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Invalid input");
                }
            }
        }
    }
}

出力結果

Enter the nuimber of cards to pick(quit): 10
6 of Diamonds
King of Spades
Enter the nuimber of cards to pick(quit): 0
Enter the nuimber of cards to pick(quit): 1
6 of Spades
Enter the nuimber of cards to pick(quit): 2
Queen of Spades
8 of Diamonds
Enter the nuimber of cards to pick(quit): 10
7 of Spades
Queen of Clubs
4 of Clubs
7 of Clubs
4 of Spades
Queen of Clubs
6 of Clubs
9 of Diamonds
Ace of Clubs
4 of Hearts
Enter the nuimber of cards to pick(quit): 10
10 of Diamonds
5 of Hearts
8 of Hearts
3 of Hearts
7 of Hearts
3 of Spades
3 of Diamonds
Queen of Diamonds
6 of Hearts
9 of Hearts
Enter the nuimber of cards to pick(quit): quit