If the user enters such number in the console will do an action

Asked

Viewed 328 times

0

How do you when the user enters such a number in the Console will do an action?

For example:

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

In case I don’t need what will happen because I already have code, I’m just wondering how to check if the user type 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();
  • You can use conditional structures... take a look at this post https://answall.com/a/41504/11404

  • Okay I tried to do but I did not succeed, I can not make him check whether it is 1 or 2

  • right, put the code snippet you are getting the user input and the way you are doing to validate the input data

  • log.Warnformat("1 or 2"); string typed = Console.Readline(); var numero = 1; if (numero == 1) coupons(); if (numero == 2) cuponsusuario();

1 answer

0


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

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");
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.