1

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;
    }
}
3
  • 2
    What is the value of læn exactly? Debug and tell us. Nov 17, 2014 at 12:24
  • You probably want Console.ReadKey() instead of Console.Read() Nov 17, 2014 at 12:30
  • probably because of 'figur = Console.Read()' Nov 17, 2014 at 12:30

2 Answers 2

7

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
  • Thanks this explained what was wrong very nicely. We got it to work now :) Nov 17, 2014 at 12:48
1

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.

1
  • 1
    Maybe in this case it is more intuitive for OP to use KeyChar. Nov 17, 2014 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.