-6

I make a program in which you can calculate an amount. And get a result out of it now that it works when I run operator 1 + 1, but not without spaces like 1 + 1. Now I want it to work in both cases. Can anyone help me with this? Since I don't know if that is also possible in my code.

I thought of removing all the spaces in my string and then splitting each character. So first replace (replace) all spaces in your string with string.Empty and then you split on an empty character.

Maybe someone can help me out?

This is my code

    private char[] SPACE = new char[] { ' ' };
    private void GetAnswer(string clipboardText)
    {
        //Loop through all questions and answers
        foreach (question q in questionList)
        {
            //If we have found an answer that is exactly the same show an Notification

            //Startwith zoekt naar alle vragen die matchen vanaf het begin van de zin en Endwith alle vragen die matchen vanaf het eind van de zin//
            if (q._question.StartsWith(clipboardText) || q._question.EndsWith(clipboardText))
            {
                ShowNotification(q._question, q._answer);
                break;
            }
        }
        var parts = clipboardText.Split(SPACE);
        var isValid = true;
        Double a, b;

        // Make sure it's format A # B
        if (parts.Length != 3)
            return;

        // Parse first number
        isValid = Double.TryParse(parts[0], out a);
        if (!isValid)
            return;

        var validOperators = new char[] { '+', '-', ':', 'x' };

        // Parse operator
        if (parts[1].Length != 1)
            return;
        var op = parts[1][0];
        if (!validOperators.Contains(op))
            return;

        // Parse 2nd number
        isValid = Double.TryParse(parts[2], out b);
        if (!isValid)
            return;

        // Now calculate the answer
        string answer = null;
        switch (op)
        {
            case '+':
                answer = (a + b).ToString();
                break;
            case '-':
                answer = (a - b).ToString();
                break;
            case ':':
                if (b == 0)
                    answer = "NaN";
                else
                    answer = (a / b).ToString();
                break;
            case 'x':
                answer = (a * b).ToString();
                break;
            default:
                throw new InvalidOperationException();
        }

        // Show the answer
        ShowNotification(clipboardText, answer);
    }
  • @Meltheny can you give a example in code ? –  May 09 '19 at 08:25
  • *"Make sure it's format A # B"* - you aren't doing this properly. The easiest approach is to use loop over input string with state machine, where first you are reading A, then #, then B. After loops is finished you should be at state "Done", with all data parsed and ready to calculate. Otherwise string was not in valid format. – Sinatr May 09 '19 at 08:27
  • @Sinatr can you give a code example on how to do it more properply? thanks in advance –  May 09 '19 at 08:33

2 Answers2

2

Your thought about removing all spaces is a good approach. Spaces are not needed for such an expression to be correct.

After removing all white spaces you should split the string into possible symbols. A number is a valid symbol and any of the operators is, too. Then you should evaluate the symbols and do the calculation.

Try searching for articles regarding "Infix Parser". Because that's what you want to do. You have a term in infix notation and want to parse it. A good start to read might be this answer: https://stackoverflow.com/a/13856790/797200

Torben Schramme
  • 2,104
  • 1
  • 16
  • 28
  • can someone give me a code example ? thanks in advance –  May 09 '19 at 08:27
  • 6
    No. I gave you some keywords to start research. I even did a search for you and gave you a link to a good answer with lots of information to your problem. And only about 100 seconds after my answer you're asking for code? Did you even read what I've written? Take your time, try to understand the linked answer, do some research, try to write code. And then when it comes to an actual problem, ask a specific question. Sorry but I won't do your work. Please show some more effort. – Torben Schramme May 09 '19 at 08:33
1

In case you want a way to replace the text with space before parsing the expression you can first remove space from expression, then check for what operator used and split the expression by it, like the following:

    //var parts = clipboardText.Split(SPACE); this should be commented since you need to remove spaces
    var textWithoutSpace = clipboardText.Replace(" ", "");
    var isValid = true;
    Double a, b;
    char currentOperator = '\0';
    //No need for this
    // Make sure it's format A # B
    //if (parts.Length != 3)
        //return;
    var validOperators = new char[] { '+', '-', ':', 'x' };

    foreach(var validOperator in validOperators)
    {
        if(textWithoutSpace.Contains(validOperator))
        {
            currentOperator = validOperator;
            break;
        }
    }
    if(currentOperator == '\0') {return;}

    var parts = textWithoutSpace.Split(currentOperator);
    //Then continue your work to take parts[0] and parts[1] and apply the operator

However above code assumes only that you need to parse expressions in the form of (A operand B), in case you need to parse more complex operations you need whether to find a ready made library that handles the dirty work for you, or to implement some of the algorithms that handles this task one of them is:

Shunting Yard Algorithm

Ali Ezzat Odeh
  • 2,093
  • 1
  • 17
  • 17
  • you might be able to edit the code for now so that it works with my code i get a lot of erros. –  May 09 '19 at 08:53
  • what do i have to replace in my code currentOperator is a error –  May 09 '19 at 09:01
  • case '+': answer = (a + b).ToString(); break; Local variable a is a error –  May 09 '19 at 09:10
  • 3
    The answer gives only guidelines to solve your problem, we are not supposed to code review here at StackOverflow you can post your full code to Code Review Exchange, but as a little help note make sure that you are assigning a and b to parts[0] and parts[1] – Ali Ezzat Odeh May 09 '19 at 09:25