0

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.

ultex113
  • 1
  • 1
  • https://stackoverflow.com/questions/16100/convert-a-string-to-an-enum-in-c-sharp – pm100 Mar 03 '22 at 01:13
  • 1
    Does the assignment actually TELL you to use an ENUM and then convert the user input using that enum?...or is that something that you came up with on your own? It seems an unlikely approach for both a STUDENT assignment and for someone who is "not a programmer". I'd expect to see some kind of `if...else if` structure, a `switch`, or maybe a search of an `Array`. Can you post more actual REQUIREMENTS or DESCRIPTION of the assignment? – Idle_Mind Mar 03 '22 at 02:08

2 Answers2

0

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)
...
tymtam
  • 31,798
  • 8
  • 86
  • 126
0

Perhaps consider avoiding enums entirely:

int month = DateTime.TryParse($"1 {input} 2022", out DateTime value) ? value.Month : -1;
Enigmativity
  • 113,464
  • 11
  • 89
  • 172