-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.
What is the advantage of using a
TryParse()
and ignore their return?– Maniero