Search code examples
c#switch-statementdefault

switch statement reverting to default regardless of user input?


What I want the program to do is ask for user input, take a number 1-7, and spit out the correct WriteLine statement. Everything compiles fine but I get the default WriteLine option no matter what number I enter. Where am I going wrong?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace week4discussion
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter a number: ");
            int userInput = Console.Read();

            switch (userInput) {
                case 1:
                    Console.WriteLine("Your selected course is IT 145");
                    break;
                case 2:
                    Console.WriteLine("Your selected course is IT 200");
                    break;
                case 3:
                    Console.WriteLine("Your selected course is IT 201");
                    break;
                case 4:
                    Console.WriteLine("Your selected course is IT 270");
                    break;
                case 5:
                    Console.WriteLine("Your selected course is IT 315");
                    break;
                case 6:
                    Console.WriteLine("Your selected course is IT 328");
                    break;
                case 7:
                    Console.WriteLine("Your selected course is IT 330");
                    break;
                default:
                    Console.WriteLine("Please enter a number 1-7");
                    break;

            }
        }
    }
}

Solution

  • You need this:

     int userInput = Convert.ToInt32(Console.ReadLine());