¿Cómo detecto un error en un int analizado desde una cadena?

I am having trubble finding a way that works and helps to catch an error input. I need to handle if the input is not a 1 or a 2. Like . or a - or just any letter. I have tried catch and well nothing seems to work :/

Someone that have an idea for me to try? I am greatfull for any suggestions!! Thx in advance!

saludos

The code i have written so far looks like this:

console.WriteLine();
Console.Write("Make your choice: ");


int myinput = int.Parse(Console.ReadLine());

if (myinput == 1)
{
FirstEvent();
}
if (myinput == 2)
{
SecondEvent();
}

preguntado el 04 de julio de 12 a las 10:07

1 Respuestas

Usually we use the TryParse methods

int myinput = 0;
if(false == int.TryParse(Console.ReadLine(), out myInput))
   // Error, not an integer
   Console.WriteLine("Please input 1 or 2");
else
{
    if (myinput == 1) 
    { 
        FirstEvent(); 
    } 
    else if (myinput == 2) 
    { 
        SecondEvent(); 
    } 
    else
        Console.WriteLine("Please input 1 or 2");
}

Respondido 04 Jul 12, 10:07

Is there a reason I don't know to write if(false == int.TryParse(Console.ReadLine(), out myInput)) instead of just if(!int.TryParse(Console.ReadLine(), out myInput))? - francesco baruchelli

@FrancescoBaruchelli, no there is no specific reason. I prefer that way because (at my age) sometimes the NOT character escapes my eyesight. - Steve

I bow my head at your kung-fu! Thanks a million Steve!! It works like a charm! Have a wonderful day! Regards - user1501127

@user1501127, thanks for your kind words. Seeing that you have just joined SO I wish to bring to your attention ¿Cómo funciona aceptar una respuesta? - Steve

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.