-3

I have some problems with using enums with switch.My task is to enter the name of the country and then show which part of the world is that one. I can't read enums from the keyboard.Did I make mistakes?Thanks for the help. `

class Program
    {
        enum Country{ Spain,USA,Japan };
        static void Main(string[] args)
        {
            Country country = new Country();
            Console.WriteLine("Enter the number of country\n 1.Spain \n 2.The USA \n 3.Japan");
            country = Console.ReadLine();
            switch (country)
            {
                case Country.Spain:
                    Console.WriteLine("Its in Europe");
                    break;
                case Country.USA:
                    Console.WriteLine("Its in North America");
                    break;
                case Country.Japan:
                    Console.WriteLine("Its in Asia");
                    break;`enter code here`
            }
            Console.ReadKey();
        }
    }
Lavander.B
  • 3
  • 1
  • 2

1 Answers1

1

You need to TryParse the string into Enum:

enum Country { Spain, USA, Japan };
static void Main(string[] args)
{
    Country country;
    Console.WriteLine("Enter the number of country\n 1.Spain \n 2.The USA \n 3.Japan");
    string input = Console.ReadLine();
    bool sucess = Enum.TryParse<Country>(input, out country);

    if (!sucess)
    {
        Console.WriteLine("entry {0} is not a valid country", input);
        return;
    }

    switch (country)
    {
        case Country.Spain:
            Console.WriteLine("Its in Europe");
            break;
        case Country.USA:
            Console.WriteLine("Its in North America");
            break;
        case Country.Japan:
            Console.WriteLine("Its in Asia");
            break;
    }
    Console.ReadKey();
}
Zein Makki
  • 29,485
  • 6
  • 52
  • 63