public final String[] tag = {"+", "-", "*", "/", "%", "(", ")"}public int divide(String input) { int result = 0; Vector<int> = new Vector<int>(); 从头到尾检索字符串,添加整数到中,整数的值为符号(+-等)的种类,若为数字则整数为-1 /////////将字符串按运算优先级拆开,然后调用calculate方法单独运算 if(已将字符串化为最短形式)//即只剩单个运算符时 { return calculte(input.substring(**,**)); } else { result += divide(input.substring(**,**)); result += divide(input.substring(**,**)); result += divide(input.substring(**,**)); } ............. return result; }public int calculate(String part) { ////////计算结果 }
{
int result = 0;
Vector<int> = new Vector<int>();
从头到尾检索字符串,添加整数到中,整数的值为符号(+-等)的种类,若为数字则整数为-1
/////////将字符串按运算优先级拆开,然后调用calculate方法单独运算
if(已将字符串化为最短形式)//即只剩单个运算符时
{
return calculte(input.substring(**,**));
}
else
{
result += divide(input.substring(**,**));
result += divide(input.substring(**,**));
result += divide(input.substring(**,**));
}
.............
return result;
}public int calculate(String part)
{
////////计算结果
}
//本程序可以实现实数的加减乘除四则运算,
import java.util.*;
import java.util.regex.*;
/**
*
*/
public class Expression{
//优先级数组,precede[i][j],表示第i个操作符与第j个操作符的优先级,0,1,2,3,4,5,6分别是'+', '-', '*', '/', '(', ')', '#'
//0表示,第i个操作符优先级小于第j个操作符。1表示大于,2表示相等,3是表示不可能的。
private int precede[][]={{1 , 1 , 0 , 0 , 0 , 1 , 1},
{1 , 1 , 0 , 0 , 0 , 1 , 1},
{1 , 1 , 1 , 1 , 0 , 1 , 1},
{1 , 1 , 1 , 1 , 0 , 1 , 1},
{0 , 0 , 0 , 0 , 0 , 2 , 3},
{1 , 1 , 1 , 1 , 3 , 1 , 1},
{0 , 0 , 0 , 0 , 0 , 3 , 2}};
private char[] operator={'+', '-', '*', '/', '(', ')', '#'};
private String infixExpression=null;
private ArrayList<MetaData> postfixExpression=new ArrayList<MetaData>();
public Expression(String exp){
infixExpression=exp+"#";
}
/**定义一个内部类表示表达式中的"元数据",操作数,或者是操作符,只能是两者之一.
*
*
*/
private class MetaData{
double dData; //float operand
int iData; // int operand
char operator; //operator
boolean isOperator=false;
MetaData(double dNum){
dData=dNum;
}
MetaData(int iNum){
iData=iNum;
}
MetaData(char operator){
this.operator=operator;
isOperator=true;
}
public boolean isOperand(){
return !isOperator;
}
public String toString(){
if(isOperator){
return ""+operator;
}else{
return ""+dData;
}
}
}//end of inner class MetaData
/**由中缀表达式得到后缀表达式。
* 设一个堆栈,用来存放操作符,先放一个自定义的操作符’#’,它的优先级是最小的。
* 扫描整个中缀表达式,操作数直接输出到结果postfixExpression中
* 如果是操作符,就和堆栈栈顶操作符比较,如果栈顶的优先级高则出栈并输出到结果,直到找到优先小的运算符为止。
* 如果两者优先级相同,表示是配对的括号,或'#'。
* 把当前的操作入栈。
*/
private void getPostfixExp(){
Stack<Integer> optrStack=new Stack<Integer>(); // Integer is a index of operator.
int index=0; // index: index of charachter in infixExpression.
double num=0; //
char c=0; //
optrStack.push(6); //'#' index is 6
//下面的正则用来提取一个数值
//
String regex="([-]?[0-9]+(\\.([0-9]+)?)?)";
Pattern numberPattern=Pattern.compile(regex);
Matcher numberMatcher=numberPattern.matcher(infixExpression);
while(index<infixExpression.length()){
if(numberMatcher.find(index)){
if(numberMatcher.start()==index){
num=Double.parseDouble(numberMatcher.group(1));
postfixExpression.add(new MetaData(num));
index=numberMatcher.end();
}
}
c=infixExpression.charAt(index++);
switch(precede[optrStack.peek()][getOperatorOrder(c)]){ //compare operator in stack with operator in c . get precede.
case 0 : //precede is 0 . means operator'precede in stack small than in c
optrStack.push(getOperatorOrder(c));
break;
case 1 :
while(precede[optrStack.peek()][getOperatorOrder(c)]==1){
postfixExpression.add(new MetaData(operator[optrStack.pop()]));
}
if(precede[optrStack.peek()][getOperatorOrder(c)]==2){
optrStack.pop(); //pop '('
}else{
optrStack.push(getOperatorOrder(c));
}
break;
case 2 :
optrStack.pop();
break;
case 3 :
System.out.println("括号不配对Expression Error!");
System.exit(0);
}//switch
}//while
}
/*对后缀表达式求值。
* 扫描整个后缀表达式,如果是数值,直接入栈。如果是运算符,出栈两个操作数,运算后,再把结果入栈。
*
*/
public double evaluate(){
getPostfixExp();
Stack<Double> valueStack=new Stack <Double>();
//System.out.println(postfixExpression);
for(MetaData md : postfixExpression){
if(md.isOperand()){
valueStack.push(md.dData);
}else{
double num1=valueStack.pop();
double num2=valueStack.pop();
valueStack.push(binaryOperation(num2,getOperatorOrder(md.operator),num1));
}
//System.out.println(valueStack);
}
return valueStack.pop();
}
/*取得操作符的序号,主要是为了比较优先级时,方便的访问precede这个二维数组。
*/
private int getOperatorOrder(char optr){
int order;
switch(optr){
case '+': order=0; break;
case '-': order=1; break;
case '*': order=2; break;
case '/': order=3; break;
case '(': order=4; break;
case ')': order=5; break;
case '#': order=6; break;
default : order=-1;
}
return order;
}
/*对两个操作数据进行运算。
*/
private double binaryOperation(double operand1,int opt,double operand2 ){
switch(opt){
case 0:
return operand1+operand2;
case 1:
return operand1-operand2;
case 2:
return operand1*operand2;
case 3:
return operand1/operand2;
}
return 0;
}
public static void main(String[] args){
Expression e=new Expression("((1+-33)*3+(2+2)*5)/-4");
//Expression e=new Expression("1+5");
System.out.println(e.evaluate()); }
}
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;public class JavaAndScript {
public static void main(String[] args){
ScriptEngineManager factory=new ScriptEngineManager();
ScriptEngine engine=factory.getEngineByName("JavaScript");
try{
String str1="15+20/2*3-10";
System.out.println(engine.eval(str1)); }catch(Exception ex){
ex.printStackTrace();
}
}
}
不过程序中有一点问题
Stack<Integer> optrStack=new Stack<Integer>();
不建议使用Stack进行栈操作,因为Stack继承自Vector,它拥有Vector的所有特点和行为,因此Stack是一个不应该被使用的旧容器,现在可以用LinkedList实现栈的行为,使用它的addFirst和removeFirst等方法
发个自己写的解析程序,工作中能用脚本还是用脚本吧,毕竟人家的程序已经
了许多应用的检验,错误会少许多。
http://topic.csdn.net/u/20090826/13/82cd6ce3-7065-4401-8a45-1e64751190c8.html
import bsh.Interpreter;public class Test1 { public static void main(String[] args) {
String expression = "15+20/2*3-10";
Object result = eval(expression);
System.out.println(expression + "=" + result);
} public static Object eval(String expression) {
Interpreter interpreter = new Interpreter();
Object obj = null;
try {
obj = interpreter.eval(expression);
} catch (EvalError e) {
e.printStackTrace();
}
return obj;
}
}