If the user types such a number on the console, they will do an action

0

How do you do when the user types such a number in the Console to do an action?

For example:

Console.WriteLine("Escreva 1 para acontecer algo, 2 para acontecer outra coisa");

In case I do not need what will happen because I already have code, I am only in doubt as to how to check if the user types 1 or 2, and give an action for a certain number

log.WarnFormat("1 ou 2");
string escreveu = Console.ReadLine();
var numero = 1;
if (numero == 1) cupons();
if (numero == 2) cuponsusuario();
    
asked by anonymous 30.08.2017 / 13:53

1 answer

0

You need to read the entry using Console.ReadLine() . The Console.ReadLine always returns a string . So if you want to do some numerical comparison you will have to convert to integer before.

For example:

Console.WriteLine("Escreva 1 para acontecer algo, 2 para acontecer outra coisa");
var strEntrada = Console.ReadLine();

int input;
if(int.TryParse(strEntrada, out input))
{
    switch(input)
    {
        case 1: 
            FazerAlgo();
            break;
        case 2: 
            FazerOutraCoisa();
            break;
    }            
}
else
{
    Console.WriteLine("Valor inválido");
}
    
30.08.2017 / 14:11