public abstract class Expression {
public abstract int interpreter(HashMap<String, Integer> var);
}
public abstract class SymbolExpression extends Expression{
protected Expression left;
protected Expression right;
public SymbolExpression(Expression _left,Expression _right){
this.left = _left;
this.right= _right;
}
}
/**
* 减法解析器
* @author Administrator
*/
public class SubExpression extends SymbolExpression{
public SubExpression(Expression _left, Expression _right) {
super(_left, _right);
}
public int interpreter(HashMap<String, Integer> var) {
return super.left.interpreter(var) - super.right.interpreter(var);
}
}
/**
*
* 加法解析器
* @author Administrator
*/
public class AddExpression extends SymbolExpression{
public AddExpression(Expression _left,Expression _right){
super(_left, _right);
}
public int interpreter(HashMap<String, Integer> var) {
return super.left.interpreter(var) + super.right.interpreter(var);
}
}
/**
* 封装解析器
* @author Administrator
*/
public class Calculator {
private Expression expression;
public Calculator(String expStr){
Stack<Expression> stack = new Stack<Expression>();
char[] charArray = expStr.toCharArray();
Expression left = null;
Expression right= null;
for(int i=0; i<charArray.length; i++){
switch (charArray[i]) {
case '+' :
left = stack.pop();
right = new TerminalExpression(String.valueOf(charArray[++i]));
stack.push(new AddExpression(left, right));
break;
case '-' :
left = stack.pop();
right = new TerminalExpression(String.valueOf(charArray[++i]));
stack.push(new SubExpression(left, right));
break;
default:
stack.push(new TerminalExpression(String.valueOf(charArray[i])));
break;
}
}
this.expression = stack.pop();
}
/**
* 开始运算
* @param var
*/
public int run(HashMap<String, Integer> var){
return this.expression.interpreter(var);
}
}
public class TerminalExpression extends Expression{
private String key;
public TerminalExpression(String _key){
this.key = _key;
}
public int interpreter(HashMap<String, Integer> var) {
return var.get(this.key);
}
}
/**
* 解释器模式
* @author Administrator
*/
public class Client {
public static void main(String[] args) throws IOException{
String expStr = getExpStr();
HashMap<String, Integer> var = getValue(expStr);
Calculator cal = new Calculator(expStr);
System.out.println("运算结果为:"+expStr +"=" + cal.run(var));
}
public static String getExpStr() throws IOException{
System.out.println("请输入表达式:");
return (new BufferedReader(new InputStreamReader(System.in))).readLine();
}
public static HashMap<String, Integer> getValue(String expStr) throws IOException{
HashMap<String, Integer> map = new HashMap<String, Integer>();
for(char ch : expStr.toCharArray()){
if(ch != '+' && ch != '-'){
if(!map.containsKey(String.valueOf(ch))){
System.out.println("请输入 "+ch+" 的值:");
String in = (new BufferedReader(new InputStreamReader(System.in))).readLine();
map.put(String.valueOf(ch), Integer.valueOf(in));
}
}
}
return map;
}
}
运行结果:
请输入表达式:
a+b-c
请输入 a 的值:
100
请输入 b 的值:
2
请输入 c 的值:
101
运算结果为:a+b-c=1