Index('+') works but Index('*') is not working?

Asked

Viewed 64 times

-1

The following code is a simple calculator that accepts two numbers and applies +, *, - or /. and the input of the signal + is working well:

input = Console.ReadLine();
while (input.Contains("+"))
{
    int result;
    int plusIndex = input.IndexOf('+');
    Int32.TryParse(input.Substring(0, plusIndex), 
                out int number1);
    Int32.TryParse(input.Substring(plusIndex, input.Length - plusIndex), 
                out int number2);
    result = number1 + number2;
    Console.WriteLine(result);
    input = input.Remove(plusIndex, 1);
}

The result is always correct, but the sign * is not working because number2 is always 0 for some reason:

input = Console.ReadLine();
while (input.Contains("*"))
{
    int result;
    int timesIndex = input.IndexOf('*');
    Int32.TryParse(input
        .Substring(0, timesIndex), 
            out int number1);
    Int32.TryParse(input
        .Substring(timesIndex, input.Length - timesIndex), 
            out int number2);
    result = number1 * number2;
    Console.WriteLine(result);
    input = input.Remove(timesIndex, 1);
}

I don’t understand why, since the code is basically the same.

  • 1

    What is the advantage of using a TryParse() and ignore their return?

2 answers

2


Summary:

There is a logic problem.
The ideal is to do the Substring using the number index, not the operator’s.

Why it works on one and not on the other?

In the code input.Substring(plusIndex, input.Length - plusIndex) is returned "+x" (being x the reported value), hence the TryParse can convert to int.

In the case of multiplication Substring is returned *x, then the converter can’t do the conversion to int.

  • Thank you, that makes a Lot of sense! I was wondering Why it was also Working with - but not with *.

0

In the lines in which it is written :

Int32.TryParse(input.Substring(timesIndex, input.Length - timesIndex), out int number2);

Replace with:

Int32.TryParse(input.Substring(plusIndex + 1, input.Length - plusIndex - 1), out int number2);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.