Here is my assignment: In your program, ask the user to enter the name of a month. Your program will output the corresponding value for that month.
Example of desired output:
Enter the name of a month: April
April is month 4
Here is my current code. I'm not a programmer, and I've somehow kind of reversed the point of the exercise:
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine("Enter the name of a month: ");
String month1 = System.Console.ReadLine();
Months month = (Months)Convert.ToInt32(month1);
System.Console.WriteLine(month);
}
}
enum Months
{
January = 1,
February = 2,
March = 3,
April = 4,
May = 5,
June = 6,
July = 7,
August = 8,
September = 9,
October = 10,
November = 11,
December = 12,
}
The output of mine requires the number of the month, then gives the actual month. Thank you.
CodePudding user response:
Have a look at Enum.Parse Method.
The exmple in the Remarks section even shows how to handle values that are not defined:
string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" }; foreach (string colorString in colorStrings) { try { Colors colorValue = (Colors) Enum.Parse(typeof(Colors), colorString); if (Enum.IsDefined(typeof(Colors), colorValue) ...
CodePudding user response:
Perhaps consider avoiding enums entirely:
int month = DateTime.TryParse($"1 {input} 2022", out DateTime value) ? value.Month : -1;