0

I am learning my first ever programming language - which is C#.

I am making my first project in my apprenticeship which is teaching me C#. It is to produce a basic calculator.

The basic calculator takes a string input and provides a result. For example, input: "5 + 5". The answer will be 10 in a decimal format.

However, part of my validation is make the even indexes of the string array only be numbers, whilst the odd indexes of the string array can only be operators of "+", "-", "*", "/". How would I do this?

I have tried to do it here but I am struggling:

for (int index = 0; index <= calculatorInput.Length; index++)
{
    if (index % 2 == 0)
    {
        if (Decimal.TryParse(calculatorInput[index]))
        {
            throw new CalculatorException("Even indexes must contain a number");
        }
        //check for number
    }
    else if (//code here)
    {
        throw new CalculatorException("Odd indexes must contain an operator");
        //check for operator
    }
}

Sorry if this question is too simple, but I would greatly appreciate the help!

Rufus L
  • 36,127
  • 5
  • 30
  • 43
Suraj Cheema
  • 103
  • 1
  • 7
  • 1
    If you are validating that the odd index is the operator, what happens when someone enters `10+10`? – maccettura Nov 01 '19 at 18:51
  • 1
    `decimal temp; if (decimal.TryParse(calculatorInput[index].ToString(), out temp)){}` The `TryParse` method takes a `string` and an `out` parameter, which you are missing. But there are better ways to do what you want. – Rufus L Nov 01 '19 at 18:58
  • Perhaps this may help tou: https://stackoverflow.com/questions/2859111/c-sharp-math-calculator/2859130#2859130 and https://stackoverflow.com/questions/57424310/need-help-improving-basic-c-sharp-calculator and https://stackoverflow.com/questions/28767906/c-sharp-calculator-application and https://stackoverflow.com/questions/20830291/c-sharp-project-simple-calculator –  Nov 01 '19 at 18:58
  • A real functioning calculator is more complex than you might think. You can get it to work for one of those 4 operations on a 2 single-digit numbers, but then you'll want to make it work for numbers consisting of more digits or for more complex operations including multiple operators. This can grow into producing parsers and execution engines that can be quite complicated. – itsme86 Nov 01 '19 at 19:00
  • Also, don't forget about negative numbers! `-1 + 3` – Rufus L Nov 01 '19 at 19:04
  • @maccettura I have some validation in the rest of the program that only allows for one number first. It splits the string with spaces as the delimiter. An error will say invalid input – Suraj Cheema Nov 01 '19 at 21:51
  • @RufusL Hey! Thank you for the reply, I am using this now. What are the better ways if I may ask? I'll definitely look into minus numbers. Also, just curious what is the out parameter and what does it do? Thanks! – Suraj Cheema Nov 01 '19 at 21:51
  • Well, you can use `if (char.IsDigit[calculatorInput[index])`, to validate that a single `char` is a number, for example. A little less fussy than `TryParse`. But I think there's hesitation to post an answer here because the "right" way to parse an equation string is fairly complicated. – Rufus L Nov 01 '19 at 21:56
  • For a first pass at it, if we were to ignore order of operations for the time being, you might start with two lists: one with numbers and one with operators. Populate these lists as you walk through the string (`"3+5-2-1+4"`). Then you could start with the first number, and then alternate taking an operator and a number, doing a calculation, taking an operator and another number, doing the next calculation, etc. It would be excellent practice for determining delimeters, validating decimal numbers, etc. But once you have to apply order of operations to the equasion, that design doesn't scale. – Rufus L Nov 01 '19 at 22:07
  • The operator would likely just indicate which of your custom methods to call to get the current result (i.e. `'+'` means call `Add(num1, num2)`, and `'-'` means call `Subtract(num1, num2)`, etc. – Rufus L Nov 01 '19 at 22:10
  • @RufusL Too many comments seem to ignore the fact that `calculatorInput` is specified as `string[]` and is not `string`. – NetMage Nov 02 '19 at 00:01
  • You say you are struggling, but what are you struggling with? Your code seems functional to me... Are you looking for `if (!"+-*/".Contains(calculatorInput[index]))` to check for not an operator? – NetMage Nov 02 '19 at 00:02
  • @NetMage I'm not sure it's clearly one or the other. I'm assuming a `string` based on his statement, *"The basic calculator takes a **string input** ... For example, **input: "5 + 5"**"*, but later he does say *"part of my validation is make the even indexes of the **string array** only be numbers"*, and the title says ***string array*** as well, so it's unlcear to me. – Rufus L Nov 02 '19 at 00:07
  • @RufusL Well, I don't think there is a version of `Decimal.TryParse` that takes `char`? – NetMage Nov 02 '19 at 00:15
  • @NetMage, correct, nor is there one that doesn't have an `out` parameter, which was my first comment (the second one on this question). But you definitely have a point. Can't wait to find out what the type really is, now! :D – Rufus L Nov 02 '19 at 00:17
  • Expecting someone to post a fully functional calculator might be a bit unrealistic. Also, your question is about even indices in a string, will you settle for the explicit answer to your question or will you edit your question? – Javier Silva Ortíz Nov 02 '19 at 01:04

2 Answers2

0

My apologies for the late response. The comment from Rufus L (https://stackoverflow.com/users/2052655/rufus-l) helped to provide the solution I needed at the time.

decimal temp; if (decimal.TryParse(calculatorInput[index].ToString(), out temp)){} The TryParse method takes a string and an out parameter, which you are missing. But there are better ways to do what you want. – Rufus L Nov 1 '19 at 18:58

All answers and comments were very helpful in my development however. The calculator has been finished now though there is always room for improvement.

Suraj Cheema
  • 103
  • 1
  • 7
-1

You can focus on operators for validation. They must always be somewhere inside the input string. Minus operator is an exception here if your calculator accepts negative numbers. But if the calculator is basic and does not support negative numbers, So the code below should be enough for operator validation:

string inputString = "10 + 10";

int index = inputString.IndexOf('+');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
    throw new CalculatorException("YOUR ERROR MESSAGE");

index = inputString.IndexOf('*');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
    throw new CalculatorException("YOUR ERROR MESSAGE");

index = inputString.IndexOf('/');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
    throw new CalculatorException("YOUR ERROR MESSAGE");

index = inputString.IndexOf('-');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
    throw new CalculatorException("YOUR ERROR MESSAGE");

///Calculation code

To increase readability I did not create a nested if-else statement. After this code block, you can place your calculation code. I think it is enough for a new learner.