Question

The thing is, it works fine, it runs, but when I enter an invalid letter the program go back to label twice, it returns me the same options twice, why is that? It should return to the beginning and show me the options just one time.

namespace First_c_sharp_code
{
    class Program
    {
        static void Main(string[] args)
        {
            char livro;
            label:
            Console.Write("\n c: for computer books \n m: for mathematical books \n h: for   history books \n e: for English books");
            livro = (char)Console.Read();

            switch (livro) 
            { 
                case 'c':
                    Console.WriteLine("Aprendendo C#");
                    break;
                case 'm':
                    Console.WriteLine("Somando com Pokemon");
                    break;
                case 'h':
                    Console.WriteLine("Brasil dos Índios");
                    break;
                case 'e':
                    Console.WriteLine("CCAA Book");
                    break;
                default:
                    Console.WriteLine("\n Opção Inválida. Tente novamente");
                    goto label;  
            }
        }
    }
}
Was it helpful?

Solution

This is the problem line:

livro = (char)Console.Read();

The problem is that Console.Read() only takes one character. But when you type x and press enter, there are two characters in the buffer, x and \n (newline). So when the next Console.Read() happens, it immediately returns \n, which is also invalid according to your switch, and you loop around again.

If you were to enter xxxx, you would see it loop around once for each x, until the input buffer is empty again.

Try this instead:

livro = Console.ReadLine().FirstOrDefault();

Here you read an entire line of input (excluding the \n), and take the first character (or \0 if the user just presses enter).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top