一个表达式计算器的局部代码(涉及异常 和 处理运算符号的思路)

 1 namespace Calculator
 2 {
 3     /// <summary>
 4     /// Calculator 的摘要说明。
 5     /// </summary>
 6     public class Calculator
 7     {
 8         public Calculator()
 9         {
10             //
11             // TODO: 在此处添加构造函数逻辑
12             //
13         }
14 
15         public double Calculat(string Expression)
16         {
17             double result = 0d;
18  
19             //去掉空格
20             Expression = Expression.Replace(" """);
21 
22             //运算符超过一个,抛出错误
23             if(Expression.Replace("+""").Replace("-","").Replace("X""").Replace("/""").Length 
24                 < Expression.Length - 1)
25             {
26                 throw new ApplicationException("运算符个数不能超过一个");
27             }
28             //如果没有运算符,尝试转换为数字
29             else if(Expression.Replace("+""").Replace("-","").Replace("X""").Replace("/""").Length 
30                 == Expression.Length)
31             {
32 
33                 //不能转换为数字,抛出错误
34                 try
35                 {
36                     result = double.Parse(Expression);
37                 }
38                 catch
39                 {
40                     throw new ApplicationException("输入数字错误。");
41                 }
42             }
43             //只有一个运算符的情况
44             else
45             {
46                 char[] splitChar = {'+''-''X''/'};
47 
48                 //用加、减、乘、除符号把字符串分成两短
49                 string[] number = Expression.Split(splitChar);
50                 
51                 //分别进行加、减、乘、除运算
52                 if(Expression.IndexOf("+"> 0)
53                 {
54                     result = double.Parse(number[0]) + double.Parse(number[1]);
55                 }
56                 else if(Expression.IndexOf("-"> 0)
57                 {
58                     result = double.Parse(number[0]) - double.Parse(number[1]);
59                 }
60                 else if(Expression.IndexOf("X"> 0)
61                 {
62                     result = double.Parse(number[0]) * double.Parse(number[1]);
63                 }
64                 else
65                 {
66                     //除数是零,抛出错误
67                     if(Convert.ToDouble(number[1]) == 0d)
68                     {
69                         throw new DivideByZeroException();
70                     }
71                     result = double.Parse(number[0]) / double.Parse(number[1]);
72                 }    
73             }
74             return result;
75         }
76     }
77 }
posted @ 2008-10-11 22:48  Edward Xie  阅读(246)  评论(0编辑  收藏  举报