So this is a bit of homework I have. I have to create a calculator application that asks for user input then calculates it. The input must be in an equation format. For example: " x = 3 + 8 ", " x = 6 - 3 " or x = " 6 - 3 * 9 ". My approach to this problem is to first break down the string user input and store it into an array of char:
private char[] userInput;
string input = Console.ReadLine();
input = input.Replace(" " ,"");
userInput = input.ToCharArray();
At this point, userInput will contain all char from input. Next, I look for the variable of equation by looping through the array, this should give me the first alphabet character it found:
char var = 'x';
for (int i = 0; i < userInput.Length; i++)
{
char c = userInput[i];
if (Char.IsLetter(c)){
var = c;
break;
}
}
Next, I will break the equation up with variable one side and all of the number and operator in the other side, separated by '=', then add all number and operator to a new char array:
//get '=' position
int equalPos = 0;
for (int i = 0; i < userInput.Length; i++)
{
char c = userInput[i];
if (Char.IsSymbol(c))
{
if (c.Equals('='))
{
equalPos = i;
break;
}
}
}
//add equation to new array
rightSide = new char[userInput.Length-equalPos];
int a = 0;
for (int i = equalPos + 1; i < userInput.Length; i++)
{
char c = userInput[i];
rightSide[a] = c;
a++;
}
At this point, the rightSide array will contain all of the number and operator as character. I can calculate this part by using System.Data.DataTable().Compute()
. However, if I am not allowed to use any library, how could I implement this? The equation should only contain 1 variable(always appear on the left side of the equation), four basic operators (+-/*) and no parenthesis.