/// <summary> /// Processes the pressed operation /// </summary> /// <param name="operation">Pressed operation</param> public void Operation(string operation) { if (!WholeInput.Contains("+") && !WholeInput.Contains("-") && !WholeInput.Contains("*") && !WholeInput.Contains("/")) { WholeInput = Input + " " + operation; isEqualityPressed = false; } else if (isOperationPressed && (WholeInput[WholeInput.Length - 1] == '+' || WholeInput[WholeInput.Length - 1] == '-' || WholeInput[WholeInput.Length - 1] == '*' || WholeInput[WholeInput.Length - 1] == '/')) { WholeInput = WholeInput.Remove(WholeInput.Length - 1).Insert(WholeInput.Length - 1, operation); } else { WholeInput = WholeInput + " " + Input; Calculate(); WholeInput = WholeInput + " " + operation; } isOperationPressed = true; }
/// <summary> /// Calculates the result of expression /// </summary> private void Calculate() { if (!double.TryParse(WholeInput, out double input)) { if (expression[0] == null) { expression = WholeInput.Split(' '); } else { if (WholeInput.Contains("- -")) { WholeInput = WholeInput.Replace("- -", "+ "); } if (WholeInput.Contains("+ -")) { WholeInput = WholeInput.Replace("+ -", "- "); } var newWholeInput = WholeInput.Substring(WholeInput.LastIndexOfAny(new [] { '+', '-', '*', '/' })); newWholeInput.Split(' ').CopyTo(expression, 1); } var result = 0.0; var first = Convert.ToDouble(expression[0]); var second = Convert.ToDouble(expression[2]); switch (expression[1]) { case "+": { result = first + second; break; } case "-": { result = first - second; break; } case "*": { result = first * second; break; } case "/": { if (second < 0.00000001 && second > -0.00000001) { throw new DivideByZeroException(); } result = first / second; break; } default: { throw new InvalidOperationException(); } } Input = result.ToString(); expression[0] = result.ToString(); expression[1] = null; expression[2] = null; } }