vendredi 8 octobre 2021

Decimal exemption using Catch

I'm trying to make a calculator that Display an error message when user try to use A decimal value, I'm trying to use Catch to Exemption a Decimal value and then give the user and error message like "Decimal value is invalid"

static void Main(string[] args)
    {
        Console.Write("Enter an equation:");
        string input = Console.ReadLine().Trim();
        string[] terms = input.Split(new Char[] { ' ', '+', '-', '*', '/' }, StringSplitOptions.RemoveEmptyEntries);

        int firstNumber = Convert.ToInt32(terms[0]);
        if (input[0] == '-')
        {
            firstNumber = -firstNumber;
            input = input.Remove(0, 1);
        }
        input = input.Remove(0, terms[0].Length).Trim();

        char op = input[0];
        input = input.Remove(0, 1).Trim();

        int secondNumber = Convert.ToInt32(terms[1]);
        if (input[0] == '-')
            secondNumber = -secondNumber;

        int result = 0;

        if (op == '+')
            try
            {
                result = (firstNumber + secondNumber);
            }
            catch(FormatException)
            {
                Console.WriteLine("Sorry cannot accept decimals");
            }

        else if (op == '-')
            try
            {
                result = (firstNumber - secondNumber);
            }
            catch
            {
            }

        else if (op == '*')
            try
            {
                result = (firstNumber * secondNumber);
            }
            catch
            {
            }

        else if (op == '/')
            try
            {
                result = (firstNumber / secondNumber);
            }
            catch
            {
            }


        Console.WriteLine(result);
        Console.ReadLine();
    }
}

}

I'm trying to make a calculator that Display an error message when user try to use A decimal value, I'm trying to use Catch to Exemption a Decimal value and then give the user and error message like "Decimal value is invalid"

I'm trying to make a calculator that Display an error message when user try to use A decimal value, I'm trying to use Catch to Exemption a Decimal value and then give the user and error message like "Decimal value is invalid"

I'm trying to make a calculator that Display an error message when user try to use A decimal value, I'm trying to use Catch to Exemption a Decimal value and then give the user and error message like "Decimal value is invalid"

Aucun commentaire:

Enregistrer un commentaire