user3555573
user3555573

Reputation: 21

How to implement a safety net so that my program does not crash when incorrect format is input

This is my C# program for taking a number and then an operator and another number that the user enters and then doing a simple calculation, how would I go about implementing a safety net so that no matter what the users enters, whether it be nothing or a string of unwanted characters, the program will say invalid input, try again. right now it crashes if the exactly correct input is not entered. thanks in advance. Please explain the location in my code where it would be best to implement this and the flow of logic.

using System;
class Calculation
{
    public static void Main(string[] data)
    {
        double result = Convert.ToDouble(data[0]);
        char op;
        double number;
        GetData(out op, out number);
        while (op != 'q' && op != 'Q')
        {
            switch (op)
            {
                case '+':
                    result += number;
                    break;
                case '-':
                    result -= number;
                    break;
                case '*':
                    result *= number;
                    break;
                case '/':
                    result /= number;
                    break;
            }
            Console.WriteLine("Result = " + result.ToString());
            GetData(out op, out number);
        }
    }

    static void GetData(out char anOperator, out double aNumber)
    {
        aNumber = 0;
        string line;
        Console.Write("Enter an opertor and a number or 'q' to quit: ");
        line = Console.ReadLine();
        anOperator = Convert.ToChar(line.Substring(0, 1));
        if (anOperator != 'q' && anOperator != 'Q')
            aNumber = Convert.ToDouble(line.Substring(2));
    }
}

Upvotes: 0

Views: 148

Answers (2)

async
async

Reputation: 1537

You may want to look into the Double.TryParse() method. Personally I wouldn't recommend using exceptions for user input - invalid user input is not an exceptional situation in my opinion, but something you should expect all the time. There are probably some edge cases that I missed that should be solved with exception handling - can't think of any right now.

Basically the idea here is to check all the conditions you can think of and don't let exceptions bubble up.

I'm employing the TryXXX() pattern in here. I introduced a string to get the error message from the method that gets the user input in case the input is invalid. By the way, I also replaced your loop with a do-while.

public static void Main(string[] data)
{
    if(data.Length == 0)
    {
        Console.WriteLine("No input :(");

        return;
    }

    double result;

    if(!Double.TryParse(data[0], out result))
    {
        Console.WriteLine("Invalid input: " + data[0]);

        return;
    }

    Console.WriteLine("Starting with number: " + result);

    char op;
    double number;

    string errorMessage;


    do
    {
        if(!TryGetData(out op, out number, out errorMessage))
        {
            Console.WriteLine("Invalid input: " + errorMessage);

            continue;
        }

        switch (op)
        {
            case '+':
                result += number;
                break;
            case '-':
                result -= number;
                break;
            case '*':
                result *= number;
                break;
            case '/':
                result /= number;
                break;
            default:
                Console.WriteLine("Invalid operator: " + op);
                continue;
        }

        Console.WriteLine("Result = " + result.ToString());


    } while (Char.ToLower(op) != 'q');
}

static bool TryGetData(out char anOperator, out double aNumber, out string message)
{
    aNumber = 0;
    message = null;

    Console.Write("Enter an operator and a number or 'q' to quit: ");

    var line = Console.ReadLine();

    anOperator = line[0];

    if (anOperator != 'q' && anOperator != 'Q')
    {
        if(line.Length <= 2)
        {
            // string too short
            message = "Input string too short";

            return false;
        }

        var isValidNumber = Double.TryParse(line.Substring(2), out aNumber);

        if(!isValidNumber)
        {
            message = "Invalid number: " + line.Substring(2);

            return false;
        }

        if(isValidNumber && (anOperator == '/' && aNumber == 0))
        {
            message = "Cannot divide by 0.";

            return false;
        }
    }

    return true;
}

Upvotes: 2

Mostafa Mohamed Ahmed
Mostafa Mohamed Ahmed

Reputation: 649

this is called Exception handling ... You can use try/catch like this

 try
        {
            string mystring = "this is a string and can't be converted to int ";
            int myint = int.Parse(mystring);
        }
        catch
        {
            Console.WriteLine("Please Enter a vaild Data Type");
        }

this way the app won't crush , instead it will display any error message you want

Upvotes: 0

Related Questions