//Проверка корректности скобок private bool checkBrackets(string sourceStr) { Stack <int> posOfBrackets = new Stack <int>(); Stack <char> brackets = new Stack <char>(); for (int i = 0; i < sourceStr.Length; i++) { if (sourceStr [i] == '(') { brackets.Push('('); posOfBrackets.Push(i); } if (sourceStr[i] == ')') { try{ brackets.Pop(); posOfBrackets.Pop(); } catch { ErrorExeption.checkExeption(sourceStr[i], i); return(false); } } } if (brackets.Count == 0) { return(checkOperations(sourceStr)); } else { ErrorExeption.checkExeption(brackets.Pop(), posOfBrackets.Pop()); return(false); } }
public override float Eval() { if (right.Eval() == 0.0f) { ErrorExeption.customExeption("Error: Attempt to divide by 0"); throw new ArgumentException("Attempt to divide by 0"); } return((right.Eval() != 0.0f) ? (left.Eval() / right.Eval()):float.MaxValue); }
//Проверка операций private bool checkOperations(string sourceStr) { string charsOfOperation = "+-/*."; for (int i = 0; i < sourceStr.Length; i++) { if (charsOfOperation.Contains(sourceStr[i].ToString()) && charsOfOperation.Contains(sourceStr[i + 1].ToString())) { ErrorExeption.checkExeption(sourceStr[i], i); return(false); } } return(true); }
//проверка выражения public bool checkExpression() { string enabledChars = "0123456789+-/*.()"; for (int i = 0; i < sourceStr.Length; i++) { if (!enabledChars.Contains(sourceStr[i].ToString())) { ErrorExeption.checkExeption(sourceStr[i], i); return(false); } } return(checkBrackets(sourceStr)); }
//Парсинг числа private Operation parseNumber() { Operation result = null; float val = 0.0f; int start = position; while (position < sourceStr.Length && (char.IsDigit(sourceStr [position]) || sourceStr [position] == '.' || sourceStr [position] == 'e')) { ++position; } try{ val = float.Parse(sourceStr.Substring(start, position - start)); } catch { ErrorExeption.customExeption("Can't parse '" + sourceStr.Substring(start)); throw new ArgumentException("Can't parse '" + sourceStr.Substring(start)); } result = new Number(val); return(result); }