0

I don't understand why my switch case isn't working. I'm trying to get the user input from a Console.Read variable which is converted to Int32 but the switch is jumping directly into the default case.

Main method:

    class Program {
    static void Main(string[] args) {
        Console.WriteLine("##############################################");
        Console.WriteLine("#                                            #");
        Console.WriteLine("#     1 - ADD ITEM       3 - VIEW ITEMS      #");
        Console.WriteLine("#     2 - EDIT ITEM      4 - DELETE ITEM     #");
        Console.WriteLine("#                                            #");
        Console.WriteLine("##############################################");

        // Get input from user
        int userChoice = Convert.ToInt32(Console.Read());

        // Call function that responds to user selection from main menu
        Functions function = new Functions();
        function.SelectFunction(userChoice);
    }
}

This is the switch method taken from a class called Functions:

public void SelectFunction(int choice) {
        switch (choice) {
            case 1:
                Console.WriteLine("ADD ITEM");
                /*Console.WriteLine("Please enter ID:");
                var id = Console.ReadLine();
                Console.Write("Item name: ");
                var name = Console.ReadLine();*/
                break;
            case 2:
                Console.WriteLine("EDIT ITEM");
                break;
            case 3:
                Console.WriteLine("VIEW ITEMS");
                break;
            case 4:
                Console.WriteLine("DELETE ITEM");
                break;
            default:
                Console.WriteLine("Input not found in any of the choices. Please try again.");
                Console.ReadKey();
                break;
        }
    }
e700867
  • 41
  • 9
  • 1
    Michael's answer is correct. I recommend following [this tutorial](https://learn.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-debugger?view=vs-2019) for getting started with debugging code. With the debugger, you would quickly have found that `choice` wasn't the value you expected, and that would have lead you to finding that `Console.Read()` didn't do what you thought it did. Without it debugging, all you can do is guess at what the problem might be, as you have done. – ProgrammingLlama Feb 20 '20 at 01:06
  • 1
    *Always* consult the documentation the first time you use a function/tool/method/class/etc to be sure you understand what it does (or doesnt do). Likewise, always consult the [documentation](https://learn.microsoft.com/en-us/dotnet/api/system.console.readline?view=netframework-4.8) when something doesnt work as expected so you can confirm (or amend) your expectations. The illusion of knowledge is a dangerous thing. – Ňɏssa Pøngjǣrdenlarp Feb 20 '20 at 01:11

0 Answers0