I created a console application that will take user input of any number and + or - operator for now, and returns the result. for example user can input 1+2+3+4, and result should be 10.
My problem is that I cannot figure out how to get the last number to be summed into the total result.
that mean in my code only 1+2+3 will be calculated while 4 will be ignored.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace SimpleCalculator
{
public class Program
{
public static void Main()
{
int result = 0;
int number;
string numberString = "";
Console.WriteLine("Enter numbers followed by operation eg. x+y-z");
while (true)
{
string userInput = UserInput();
//Loop into each element of the input string
for (int i = 0; i < userInput.Length; i++)
{
if((IsNumber(userInput[i])))
{
numberString += userInput[i];
}
else if (!IsNumber(userInput[i]))
{
number = Int32.Parse(numberString);
numberString = "";
result = PerformCalculation(result, number, userInput[i]);
}
}
number = Int32.Parse(numberString);
result += number;
Console.WriteLine($"{userInput}={result}");
}
}
// check if input is number or operator
static bool IsNumber(char input)
{
if (char.IsDigit(input)){return true;}
else{return false;}
}
static string UserInput()
{
string User_input = Console.ReadLine();
return User_input;
}
static int PerformCalculation(int sum, int num, char op)
{
switch (op)
{
case '+': return sum + num;
case '-': return sum - num;
default: throw new ArgumentException("Uknown operator");
}
}
}
}