Basic C # query

0

It is a number counter, if one enters OK should exit and show the sum of the numbers entered. The counter works fine but when I enter OK instead of leaving the while the application crashea.

static void Main(string[] args)      
{         
var contador = 0;       
Console.WriteLine("Ingrese un numero... Para salir presione OK");          
var numero = Console.ReadLine();        
 contador = Convert.ToInt32(numero);        
 while (numero.ToLower() != "ok")         
 {            
  Console.WriteLine("Ingrese un numero... Para salir presione OK");
  numero = Console.ReadLine();           
  contador += Convert.ToInt32(numero);     
 }

 Console.WriteLine("La suma de sus numeros es= "+contador);      
}
    
asked by Mauro Ferrantelli 04.06.2017 в 16:13
source

1 answer

1

I can not understand what he is trying to do in general. But answering your specific question, I think I would handle it like this: What they enter on the keyboard should be of the string type, search for the string that gives the output and if it does not correspond it would confirm if it is a number and for this I would use the int.TryParse () function. I leave this code to see if it helps.

  static void Main(string[] args)
    {
        int contador = 0;
        int sumaNumeros = 0;

        Console.WriteLine("Ingrese un numero... O escriba OK para salir");
        string entradaTeclado = Console.ReadLine();

        while (entradaTeclado.ToLower() != "ok")
        {
            // Si lo escrito por teclado es un numero lo guarda en esta variable
            int NumeroIngresado;
            // Verifica si el numero ingresado es numerico
            bool isNumeric = int.TryParse(entradaTeclado, out NumeroIngresado);

            if (isNumeric == true)
            {
                sumaNumeros = NumeroIngresado + contador;
            }
            Console.WriteLine("La suma de sus numeros es= " + sumaNumeros);
            entradaTeclado = Console.ReadLine();
        }
    }
    
answered by 04.06.2017 / 17:42
source