0

My program works correctly. The only thing I am trying to figure out is how to send an error for invalid user input. If a user types in strings or numbers without using spaces, "a * b", "12*5", how can I send an error in a split.

using System;

namespace Calculator1
{
    class Program
    {
        static void Main(string[] args)
        {
            double answer;
            bool Continue = true;

            Console.WriteLine("\tCalculator");
            Console.WriteLine("--------------------------\n");

            Console.WriteLine("   Math Operations: ");
            Console.WriteLine(" --------------------");
            Console.WriteLine("  Multiplication: *");
            Console.WriteLine("        Addition: +");
            Console.WriteLine("     Subtraction: -");
            Console.WriteLine("        Division: /");

            while (Continue)
            {
                Console.WriteLine("\nEnter your equation below:");
                Console.WriteLine("    For example: 5 + 5 ");

                string[] values = Console.ReadLine().Split(' ');
                double firstNum = double.Parse(values[0]); 
                string operation = (values[1]);
                double secondNum = double.Parse(values[2]);

                if (operation == "*")
                {
                    answer = firstNum * secondNum;
                    Console.WriteLine("\n" + firstNum + " * " + secondNum + " = " + answer);
                }
                else if (operation == "/")
                {
                    answer = firstNum / secondNum;
                    Console.WriteLine("\n" + firstNum + " / " + secondNum + " = " + answer);
                }
                else if (operation == "+")
                {
                    answer = firstNum + secondNum;
                    Console.WriteLine("\n" + firstNum + " + " + secondNum + " = " + answer);
                }
                else if (operation == "-")
                {
                    answer = firstNum - secondNum;
                    Console.WriteLine("\n" + firstNum + " - " + secondNum + " = " + answer);
                }
                else
                {
                    Console.WriteLine("Sorry that is not correct format! Please restart!");
                }

                Console.WriteLine("\n\nDo you want to continue?");
                Console.WriteLine("Type in Yes to continue or press any other key and then press enter to quit:");
                string response = Console.ReadLine();
                Continue = (response == "Yes");

            }
        }
    }
}

Calculator

Math Operations:


Multiplication: * Addition: + Subtraction: - Division: /

Enter your equation below: For example: 5 + 5 5*5 //I want to send an error here

Unhandled Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDouble(ReadOnlySpan`1 value, NumberStyles options, NumberFormatInfo numfmt) at System.Double.Parse(String s) at Calculator1.Program.Main(String[] args) Press any key to continue . . .

Calculator

Math Operations:


Multiplication: * Addition: + Subtraction: - Division: /

Enter your equation below: For example: 5 + 5 a * b //I also want to send an error here

Unhandled Exception: System.FormatException: Input string was not in a correct format. at System.Number.ParseDouble(ReadOnlySpan`1 value, NumberStyles options, NumberFormatInfo numfmt) at System.Double.Parse(String s) at Calculator1.Program.Main(String[] args) Press any key to continue . . .

1
  • You should use a switch case rather than n-if Commented Jul 30, 2019 at 14:22

3 Answers 3

1

This is probably what you need:

public static void Main(string[] args)
{
    double answer;
    bool Continue = true;

    Console.WriteLine("\tCalculator");
    Console.WriteLine("--------------------------\n");

    Console.WriteLine("   Math Operations: ");
    Console.WriteLine(" --------------------");
    Console.WriteLine("  Multiplication: *");
    Console.WriteLine("        Addition: +");
    Console.WriteLine("     Subtraction: -");
    Console.WriteLine("        Division: /");

    while (Continue)
    {
        Console.WriteLine("\nEnter your equation below:");
        Console.WriteLine("    For example: 5 + 5 ");

        string[] values = Console.ReadLine().Split(' ');
        try{
            double firstNum = double.Parse(values[0]); 
            string operation = (values[1]);
            double secondNum = double.Parse(values[2]);
            switch(operation){
                case "*":
                    answer = firstNum * secondNum;
                    Console.WriteLine("\n" + firstNum + " * " + secondNum + " = " + answer);
                    break;
                case "/":
                    answer = firstNum / secondNum;
                    Console.WriteLine("\n" + firstNum + " / " + secondNum + " = " + answer);
                    break;
                case "+":
                    answer = firstNum + secondNum;
                    Console.WriteLine("\n" + firstNum + " + " + secondNum + " = " + answer);
                    break;
                case "-":
                    answer = firstNum - secondNum;
                    Console.WriteLine("\n" + firstNum + " - " + secondNum + " = " + answer);
                    break;
                default:
                    Console.WriteLine("Sorry that is not correct format! Please restart!");
                    break;
            }

            Console.WriteLine("\n\nDo you want to continue?");
            Console.WriteLine("Type in Yes to continue or press any other key and then press enter to quit:");
            string response = Console.ReadLine();
            Continue = (response == "Yes");
        }
        catch(FormatException ex){
            Console.WriteLine("You entered a bad operation, try another one");
        }

    }
}

All you have to do is to catch a format exception that caused by a parse of a double (that isn't really a double). If you catch it, then you print an error message to the user.

Sign up to request clarification or add additional context in comments.

1 Comment

If this helped you, don't forget to mark this answer as a solution
0

I don't know what you mean by "send an error in a split". Split just splits a string.

Validate the input the do a Console.Writeline with your error message.

For validating the user input I suggest using TryParse instead of Parse. This avoids the exceptions and you can check if the input was valid.

And yes. Use a switch statement instead of your if else version. Ctrl-. should offer a refactoring for this.

Kind regards Bernd

Comments

0

See this solution, please:

// Your codes

while (Continue)
{
    Console.WriteLine("\nEnter your equation below:");
    Console.WriteLine("    For example: 5 + 5 ");

    string str = Console.ReadLine().Replace(" ", "");      // Remove all spaces
    string[] values = Regex.Split(str, @"([\+\-\*\/])");   // Split numbers and operator and also keep operator

    if (values.Length != 3)
    {
        Console.WriteLine("Expresion is not correct.");
    }
    else
    {
        double firstNum = double.Parse(values[0]);
        string operation = (values[1]);
        double secondNum = double.Parse(values[2]);

        switch (operation)
        {
            case "*":
                answer = firstNum * secondNum;
                break;
            case "/":
                answer = firstNum / secondNum;
                break;
            case "+":
                answer = firstNum + secondNum;
                break;
            case "-":
                answer = firstNum - secondNum;
                break;
            default:
                Console.WriteLine("Sorry that is not correct format! Please restart!");
                break;
        }
        Console.WriteLine($"{firstNum} {operation} {secondNum} = {answer}");

        Console.WriteLine("\n\nDo you want to continue?");
        Console.WriteLine("Type in Yes to continue or press any other key and then press enter to quit:");
        string response = Console.ReadLine();
        Continue = (response.ToUpper() == "YES" || response.ToUpper() == "Y");
    }
}

// Your codes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.