switch case ignores Console.ReadLine()

1.6k Views Asked by At

I am helping a friend with some beginner c#, and we have run into a weird problem.

The læn = Console.ReadLine() on line 31 is being skipped. This causes the .Parse on line 32 to throw an error.

If we put an extra læn = Console.ReadLine() in after the first one it starts working.

static void Main(string[] args)
{
    double areal, læn1, høj1 = 0;
    int figur;
    string tekst, læn, høj;

    tekst = ("Du skal nu vægle en figur.");
    tekst += ("\nTryk 1 for rektangel");
    tekst += ("\nTryk 2 for cirkel");
    tekst += ("\nTryk 3 for en retvinklet trekant");
    tekst += ("\nValg: ");
    Console.Write("{0}", tekst);
    figur = Console.Read();
    switch (figur)
    {
        case '1':
            {
                Console.WriteLine("Du har valgt en rektangel. \nHvad er længden: ");
                læn = Console.ReadLine(); //Line 31
                læn1 = double.Parse(læn); //Line 32

                Console.WriteLine("hvad er højden?");
                høj = Console.ReadLine();
                høj1 = double.Parse(høj);

                areal = læn1 * høj1;
                Console.WriteLine("\n{0} * {1} = {2}", læn, høj1, areal);

                Console.ReadKey();
            }
            break;

        default:
            Console.WriteLine("Du har ikke valgt 1,2 eller 3");
            Console.ReadKey();
            break;
    }
}
2

There are 2 best solutions below

1
On BEST ANSWER

The documentation from Console.Read states:

The Read method blocks its return while you type input characters; it terminates when you press the Enter key.

This means that it will only return a value when you press Enter, no matter how much you have written.

Since your next statement is Console.ReadLine() and there is still a line end in the stream pending to read (since you hit Enter, but only handled the key pressed), the 'eats' up that statement.

Consider using Console.ReadKey() instead.

1
On

Just to add something to what Patrick said, I recommend you replace that Console.Read() with this:

ConsoleKeyInfo figur = Console.ReadKey();
switch (figur.Key)
{
    case ConsoleKey.D1:

Also notice that all those parenthesis when you assign tekst are not necessary, as well as the brackets inside each switch's case.