How to get input with char instead of integer in c sharp

196 Views Asked by At

Hey there.

I am trying to learn C sharp by myself but i have a problem about getting input as an character. My code part is :

    var foodTypeMap = new Dictionary<string, string>();
    foodTypeMap["1"] = "Soups";
    foodTypeMap["2"] = "Vegetables";
    foodTypeMap["3"] = "Mains";
    foodTypeMap["4"] = "Deserts";
    ...
    ...
    string fType = Console.ReadLine();
    string dishType = " ";
    //if else statements here.. etc
    dishType = foodTypeMap[fType];

by this way i can get the fType as an integer and initialize the dishType by that. I want to get the choices by chars like x for soup and q for deserts. I tried

Using Console.ReadLine()[0]
Using Console.ReadKey().KeyChar
Using Char.TryParse()
Using Convert.ToChar()

but couldn't make it. Is there anyone to help me to understand that?

1

There are 1 best solutions below

0
On

To be able to get the results from the dictionary, you'll need to understand how a dictionary works. A dictionary is a key:value pair. So if you want desserts to be q, you'll need to edit the "4" as that is the key and then change it to q.

var foodTypeMap = new Dictionary<string, string>();
    foodTypeMap["x"] = "Soups";
    foodTypeMap["y"] = "Vegetables";
    foodTypeMap["m"] = "Mains";
    foodTypeMap["q"] = "Deserts";
        
   var PickFromDictionary = Console.ReadLine();
        Console.WriteLine(foodTypeMap[PickFromDictionary]);

this code will run and if you type x,y,m or q you'll get one of the dishes.

foodTypeMap["x"] = "Soups";

i changed the Key value to an x, so instead of 1, if you now input an x you'll get the "Soups" and i changed the other values to some other chars, too.

if you type something that's not in the dictionary you'll get an exception