How to improve a calculator

Asked

Viewed 38 times

0

I wonder if we can make this code not stop when I type a letter instead of a number, just correcting and telling to type a number.

namespace calculadora 
{
  class Program {
    static void Main() {
      ConsoleKey bta = ConsoleKey.A;
      while (bta == ConsoleKey.Escape == false) {
        double n1, n2;
        Console.Clear();
        n1 = double.Parse(Console.ReadLine());
        ConsoleKey mais = Console.ReadKey().Key;
        if (mais == ConsoleKey.Add) {
          Console.WriteLine(" ");
          string b = Console.ReadLine();
          n2 = double.Parse(b);
          Console.WriteLine("{0} + {1} = {2}", n1, n2, n1 + n2);
        }
        if (mais == ConsoleKey.Subtract) {
          Console.WriteLine(" ");
          string b = Console.ReadLine();
          n2 = double.Parse(b);
          Console.WriteLine("{0} - {1} = {2}", n1, n2, n1 - n2);
        }
        if (mais == ConsoleKey.Multiply) {
          Console.WriteLine(" ");
          string b = Console.ReadLine();
          n2 = double.Parse(b);
          Console.WriteLine("{0} . {1} = {2}", n1, n2, n1 * n2);
        }
        if (mais == ConsoleKey.Divide) {
          Console.WriteLine(" ");
          string b = Console.ReadLine();
          n2 = double.Parse(b);
          double Res = n1 / n2;
          Console.WriteLine("{0} / {1} = {2}", n1, n2, Res);
        }
        Console.WriteLine(" ");
        bta = Console.ReadKey().Key;

      }
    }
  }
}

1 answer

0


You can create a function to do it for you, something like that:

public double ReadNumber() 
{
  var str = Console.ReadLine();
  while (!str.All(char.IsDigit) || string.IsNullOrEmpty(str))
  {
    Console.WriteLine("Entrada inválida, digite apenas números!");
    str = Console.ReadLine();
  }
  
  return double.Parse(str);
}

public static void Main()
{
  var numero = ReadNumber();
}

Browser other questions tagged

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