Create a new readuseroption method that returns a

This preview shows page 3 - 5 out of 11 pages.

5. Create a new ReadUserOptionmethod that returns a MenuOptioninsidethe Programclass.This method will show the menu to the user and read in their selection.The ReadUserOptionmethod should perform the following steps. These are expressed hereas pseudocode(which is code like text, often used to express how an algorithm should work).Remember to add the statickeyword to this method, as we will run it directly on theProgramclass itself.privatestaticMenuOption ReadUserOption(){// steps go here...}1. Start the method by declaring an optioninteger variable. We will use this to store thevalue of the option the user selects.2. Use Console.WriteLineto output a menu showing the three options. "1 will run TestName, 2 will play Guess That Number, and 3 will Quit". Add a header and use "*" or "-" to putborders around things to make them look a little nicer.3. Start a do ... whileloop. With the following 2 steps inside the do while:1. Use Console.Writeto show the user a prompt, something like "Choose an option[1-3]: "2. Use Console.ReadLineand Convert.ToInt32to read in the user's selectionand convert it to an integer. Store this in a variable for later use in the optionvariable.4. End the do ... whileloop with a condition that checks that the value read in by the user is lessthan 1 orlarger than 3.In this way we can force the user to choose a valid option. We ask them to enter the value,then loop while it is not a valid option.
5. Lastly, we can return the matching MenuOption. We can make use of our understandingof enumerations, and the fact that each enumeration value is actually an integer. Thefollowing code will return the matching MenuOptionvalue.return(MenuOption)(option - 1);This works because each of the enumeration labels is associated with an integer valueinternally. When option is 1, the user wanted to TestName. This is the first value of theenumeration, so it has the integer value 0. Subtracting 1 from the value the user entered willconvert it to the matching enumeration value.The (MenuOption)code is a cast. This tells the computer to re-interpret the value(option - 1)as a MenuOptionvalue. This converts the 0MenuOption.TestName.Finally, the result of this cast can then be returned to the caller. They will getMenuOption.TestNameif the user entered 1, MenuOption.GuessThatNumberifthey entered 2, or MenuOption.Quitif they entered 3.
to

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture