日期:2014-05-20  浏览次数:20664 次

java能否将字符串5-3+1转化成计算公式求出值3
知道一个字符串里面可能含有+-*/运算符号,怎么将其作为计算公式直接计算,得到结果。

String   a=5-3+1;
求出5-3+1最为计算公式时的a值


------解决方案--------------------
package org.luyang.csdn;

import java.util.ListIterator;
import java.util.Stack;

public class CalStr {
private String src;

/**
* constructor
*
* @param srcthe string(expression) to calculate
*/
public CalStr(String src) {
this.src = src;
}

/**
* calculate to get the result
*
* @return(double)result
*/
public double getResult() {
String postfix = getPostfix();
Stack stk = new Stack();
// System.out.println(postfix);
String parts[] = postfix.split( " + ");
double result = 0;
for (int i = 0; i < parts.length; i++) {
char tmp = parts[i].charAt(0);
if (!isOperator(tmp)) {
stk.push(parts[i]);
} else {
double a = Double.parseDouble((String) stk.pop());
double b = Double.parseDouble((String) stk.pop());
// b is followed by a in the orignal expression
result = calculate(b, a, tmp);
stk.push(String.valueOf(result));
}
}
return result;
}

/**
* test if the character is an operator,such +,-,*,/
*
* @param opthe character to test
* @returntrue if op is an operator otherwise false
*/
private boolean isOperator(char op) {
return (op == '+ ' || op == '- ' || op == '* ' || op == '/ ');
}

/**
* calculate an expression such (a op b)
*
* @param anumber 1
* @param bnumber 2
* @param opthe operator
* @return(double)(a op b)
*/
public double calculate(double a, double b, char op) {
switch (op) {
case '+ ':
return a + b;
case '- ':
return a - b;
case '* ':
return a * b;
case '/ ':
return a / b;
}
return -1;
}

/**
* convert the suffix to postfix
*
* @returnthe postfix as a string
*/
private String getPostfix() {
Stack stk = new Stack();
String postfix = new String();
char op;
int i = 0;
while (i < src.length()) {
if (Character.isDigit(src.charAt(i)) || src.charAt(i) == '. ') {
postfix += " ";
do {
postfix += src.charAt(i++);
} while ((i < src.length())
&& (Character.isDigit(src.charAt(i))));
postfix += " ";
}

else {
switch (op = src.charAt(i++)) {
case '( ':
stk.push( "( ");
break;

case ') ':
while (stk.peek() != "( ") {
String tmp = (String) stk.pop();
postfix += tmp;
if (tmp.length() == 1 && isOperator(tmp.charAt(0)))
postfix += " ";