1700474197
}
1700474198
1700474199
}
1700474200
1700474201
方法比较长,我们来分析一下,Calculator构造函数接收一个表达式,然后把表达式转化为char数组,并判断运算符号,如果是”+“则进行加法运算,把左边的数(left变量)和右边的数(right变量)加起来就可以了,那左边的数为什么是在栈中呢?例如这个公式:a+b-c,根据for循环,首先被压入栈中的应该是有a元素生成的VarExpression对象,然后判断到加号时,把a元素的对象VarExpression从栈中弹出,与右边的数组b进行相加,b又是怎么得来的呢?当前的数组游标下移一个单元格即可,同时为了防止该元素再次被遍历,则通过++i的方式跳过下一个遍历——于是一个加法的运行结束。减法也采用相同的运行原理。
1700474202
1700474203
为了满足业务要求,我们设置了一个Client类来模拟用户情况,用户要求可以扩展,可以修改公式,那就通过接收键盘事件来处理,Client类如代码清单27-7所示。
1700474204
1700474205
代码清单27-7 客户模拟类
1700474206
1700474207
public class Client{
1700474208
1700474209
//运行四则运算
1700474210
1700474211
public static void main(String[]args)throws IOException{
1700474212
1700474213
String expStr=getExpStr();
1700474214
1700474215
//赋值
1700474216
1700474217
HashMap<String,Integer>var=getValue(expStr);
1700474218
1700474219
Calculator cal=new Calculator(expStr);
1700474220
1700474221
System.out.println(“运算结果为:”+expStr+”=”+cal.run(var));
1700474222
1700474223
}
1700474224
1700474225
//获得表达式
1700474226
1700474227
public static String getExpStr()throws IOException{
1700474228
1700474229
System.out.print(“请输入表达式:”);
1700474230
1700474231
return(new BufferedReader(new InputStreamReader(System.in))).readLine();
1700474232
1700474233
}
1700474234
1700474235
//获得值映射
1700474236
1700474237
public static HashMap<String,Integer>getValue(String exprStr)throws
1700474238
1700474239
IOException{
1700474240
1700474241
HashMap<String,Integer>map=new HashMap<String,Integer>();
1700474242
1700474243
//解析有几个参数要传递
1700474244
1700474245
for(char ch:exprStr.toCharArray()){
1700474246
[
上一页 ]
[ :1.700474197e+09 ]
[
下一页 ]