我需要帮助来简化此计划

时间:2016-10-16 11:06:50

标签: c#

        decimal sum;
        int index;

        Console.WriteLine("Enter numbers you want to calculate:");
        string Expression = Console.ReadLine();

        if (Expression.Contains("+"))
        {
            index = Expression.IndexOf("+");
            int secondnumber = index + 1;
            decimal a = decimal.Parse(Expression.Substring(0, index));
            decimal b = decimal.Parse(Expression.Substring(secondnumber));
            sum = a + b;
            Console.WriteLine("{0}={1}", Expression, sum.ToString("0.###"));
        } else if (Expression.Contains("-"))
        {
            index = Expression.IndexOf("-");
            int secondnumber = index + 1;
            decimal a = decimal.Parse(Expression.Substring(0, index));
            decimal b = decimal.Parse(Expression.Substring(secondnumber));
            sum = a - b;
            Console.WriteLine("{0}={1}", Expression, sum.ToString("0.###"));
        } else if (Expression.Contains("/"))
        {
            index = Expression.IndexOf("/");
            int secondnumber = index + 1;
            decimal a = decimal.Parse(Expression.Substring(0, index));
            decimal b = decimal.Parse(Expression.Substring(secondnumber));
            sum = a / b;
            Console.WriteLine("{0}={1}", Expression, sum.ToString("0.###"));
        } else if (Expression.Contains("*"))
        {
            index = Expression.IndexOf("*");
            int secondnumber = index + 1;
            decimal a = decimal.Parse(Expression.Substring(0, index));
            decimal b = decimal.Parse(Expression.Substring(secondnumber));
            sum = a * b;
            Console.WriteLine("{0}={1}", Expression, sum.ToString("0.###"));
        } else
        {
            Console.WriteLine("ERROR");
        }

问题是我无法简化代码而不会弄乱它并抛出异常。任何帮助将不胜感激。我还需要帮助.IndexOf方法无论如何在if选择之外吗?我一直在努力,但它一直在弄乱。

1 个答案:

答案 0 :(得分:2)

由于所有“if blocks”都遵循相同的模式:

  • 拆分1个字符的操作符
  • 向左解析小数,向运算符右侧解析小数
  • 对他们执行功能

您可以将这些功能存储在Dictionary

var functionsByOperator = new Dictionary<char, Func<decimal, decimal, decimal>>();
functionsByOperator['+'] = (left, right) => left + right;
functionsByOperator['*'] = (left, right) => left * right;
// etc

然后其余的代码变得不那么重复:

// the below array is required for the IndexOfAny method later on
char[] operators = new List<char>(functionsByOperator.Keys).ToArray();

Console.WriteLine("Enter numbers you want to calculate:");
string Expression = Console.ReadLine();

int index = Expression.IndexOfAny(operators);
if (index < 0)
{
    Console.WriteLine("ERROR");
    return;
}

decimal a = decimal.Parse(Expression.Substring(0, index));
decimal b = decimal.Parse(Expression.Substring(index + 1));
char oper = Expression[index];
decimal sum = functionsByOperator[oper](a, b);
Console.WriteLine("{0}={1}", Expression, sum.ToString("0.###"));