这是我以前收藏的东西,刚找了找。挺好的!import java.util.LinkedList; import java.util.Map; public class ExpressionUtil { public String getPostfixExp(String expression,Map<String,Integer> priorities){ LinkedList<String> opStack = new LinkedList<String>(); StringBuffer result = new StringBuffer();
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class ScriptEngineTest { public static void main(String[] args) {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByName("js");
try {
System.out.println(se.eval("1+2*(3+4)").toString());
} catch (ScriptException e) {
e.printStackTrace();
}
}}
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class ScriptEngineTest { public static void main(String[] args) {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByName("js");
try {
double d = Double.parseDouble(se.eval("(2+1)-2*1/3").toString());
System.out.println((int)Math.ceil(d));
} catch (ScriptException e) {
e.printStackTrace();
}
}}
* 格式化日期
* @param obj 日期对象
* @param format 格式化字符串
* @return
* @author ZYWANG 2009-8-26
*/
public static String formatDate(Object obj,String format){
if(obj == null) return "";
String s = String.valueOf(obj);
if(format==null|| "".equals(format.trim())){
format = "yyyy-MM-dd";
}
try{
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
s = dateFormat.format(obj);
}catch (Exception e) { }
return s;
}
/**
* 格式化数字
* @param obj 数字对象
* @param format 格式化字符串
* @return
* @author ZYWANG 2009-8-26
*/
public static String formatNumber(Object obj,String format){
if(obj == null) return "";
String s = String.valueOf(obj);
if(format==null|| "".equals(format.trim())){
format = "#.00";
}
try{
if(obj instanceof Double || obj instanceof Float){
if(format.contains("%")){
NumberFormat numberFormat = NumberFormat.getPercentInstance();
s = numberFormat.format(obj);
}else{
DecimalFormat decimalFormat = new DecimalFormat(format);
s = decimalFormat.format(obj);
}
}else{
NumberFormat numberFormat = NumberFormat.getInstance();
s = numberFormat.format(obj);
}
}catch (Exception e) { }
return s;
}
/**
* 计算字符串四则运算表达式
* @param string
* @return
* @author ZYWANG 2009-8-31
*/
public static String computeString(String string){
String regexCheck ="[\\(\\)\\d\\+\\-\\*/\\.]*";//是否是合法的表达式
if(!Pattern.matches(regexCheck, string))
return string;
Matcher matcher = null;
String temp = "";
int index = -1;
String regex = "\\([\\d\\.\\+\\-\\*/]+\\)";//提取括号表达式
string = string.replaceAll("\\s", "");//去除空格
try{
Pattern pattern = Pattern.compile(regex);
//循环计算所有括号里的表达式
while(pattern.matcher(string).find()){
matcher = pattern.matcher(string);
while(matcher.find()){
temp = matcher.group();
index = string.indexOf(temp);
string = string.substring(0, index)+computeStirngNoBracket(temp)+string.substring(index+temp.length());
}
}
//最后计算总的表达式结果
string = computeStirngNoBracket(string);
}catch (NumberFormatException e) {
return e.getMessage();
}
return string;
}
/**
* 计算不包含括号的表达式
* @param string
* @return
* @author ZYWANG 2009-8-31
*/
private static String computeStirngNoBracket(String string){
string = string.replaceAll("(^\\()|(\\)$)", "");
String regexMultiAndDivision = "[\\d\\.]+(\\*|\\/)[\\d\\.]+";
String regexAdditionAndSubtraction = "[\\d\\.]+(\\+|\\-)[\\d\\.]+";
String temp = "";
int index = -1;
//解析乘除法
Pattern pattern = Pattern.compile(regexMultiAndDivision);
Matcher matcher = null;
while(pattern.matcher(string).find()){
matcher = pattern.matcher(string);
if(matcher.find()){
temp = matcher.group();
index = string.indexOf(temp);
string = string.substring(0, index)+doMultiAndDivision(temp)+string.substring(index+temp.length());
}
}
//解析加减法
pattern = Pattern.compile(regexAdditionAndSubtraction);
while(pattern.matcher(string).find()){
matcher = pattern.matcher(string);
if(matcher.find()){
temp = matcher.group();
index = string.indexOf(temp);
string = string.substring(0, index)+doAdditionAndSubtraction(temp)+string.substring(index+temp.length());
}
}
return string;
}
/**
* 执行乘除法
* @param string
* @return
* @author ZYWANG 2009-8-31
*/
private static String doMultiAndDivision(String string){
String value = "";
double d1 = 0;
double d2 = 0;
String[] temp = null;
if(string.contains("*")){
temp = string.split("\\*");
}else{
temp = string.split("/");
}
if(temp.length<2)
return string;
d1 = Double.valueOf(temp[0]);
d2 = Double.valueOf(temp[1]);
if(string.contains("*")){
value=String.valueOf(d1*d2);
}else{
value=String.valueOf(d1/d2);
}
return value;
}
/**
* 执行加减法
* @param string
* @return
* @author ZYWANG 2009-8-31
*/
private static String doAdditionAndSubtraction(String string){
double d1 = 0;
double d2 = 0;
String[] temp = null;
String value = "";
if(string.contains("+")){
temp = string.split("\\+");
}else{
temp = string.split("\\-");
}
if(temp.length<2)
return string;
d1 = Double.valueOf(temp[0]);
d2 = Double.valueOf(temp[1]);
if(string.contains("+")){
value=String.valueOf(d1+d2);
}else{
value=String.valueOf(d1-d2);
}
return value;
} public static void main(String[] args) {
String s = "1+1";
s = computeString(s);
System.out.println(s);
System.out.println(formatNumber(Double.valueOf(s),"####.000"));
}
http://zywang.javaeye.com/blog/462797
http://www.ibm.com/developerworks/cn/java/j-w3eva/
import java.util.Map;
public class ExpressionUtil { public String getPostfixExp(String expression,Map<String,Integer> priorities){
LinkedList<String> opStack = new LinkedList<String>();
StringBuffer result = new StringBuffer();
for(Character c: expression.toCharArray()){
String cs = c.toString();
if(priorities.containsKey(cs)){
if("(".equals(cs)){
opStack.offerLast(cs);
}else if(")".equals(cs)){
while(opStack.size()>0){
String op = opStack.pollLast();
if(!"(".equals(op)){
result.append(op);
}
}
}else{
String opString = opStack.peekLast();
if(opStack.size()>0 && !"(".equals(opString)){
Integer current = priorities.get(cs);
Integer stackLast = priorities.get(opString);
if(current<=stackLast){
result.append(opStack.pollLast());
}
}
opStack.offerLast(cs);
}
}else{
result.append(cs);
}
System.out.println(opStack.toString()+":"+result);
}
while(opStack.size()>0){
result.append(opStack.removeLast());
}
return result.toString();
}
public Double getValueByPostfix(String postfix,Map<String,Double> dict,Map<String,Integer> priorities,String... e){
LinkedList<Double> numStack = new LinkedList<Double>();
StringBuffer tempDield = new StringBuffer();
for(Character c: postfix.toCharArray()){
Double temp = null;
if(priorities.containsKey(c.toString())){
Double right = numStack.pollLast();
Double left = numStack.pollLast();
if("+".equals(c.toString())){
temp = left+right;
}else if("-".equals(c.toString())){
temp = left-right;
}else if("*".equals(c.toString())){
temp = left*right;
}else if("/".equals(c.toString())){
temp = left/right;
}
System.out.println(temp+"="+left+c.toString()+right);
}else{
if(e.length==2){
if(e[0].equals(c.toString())){
tempDield.append(c.toString());
continue;
}else if(e[1].equals(c.toString())){
tempDield.append(c.toString());
temp = dict.get(tempDield.toString());
tempDield = new StringBuffer();
}else if(tempDield.length()>0 && !e[1].equals(c.toString())){
tempDield.append(c.toString());
continue;
}
}else{
temp = dict.get(c.toString());
}
System.out.println(temp);
}
numStack.offerLast(temp);
}
return numStack.getFirst();
}
public Double getValueByExpression(String expression,Map<String,Double> dict,Map<String,Integer> priorities,String... e){
String postfix = getPostfixExp(expression,priorities);
return getValueByPostfix(postfix,dict,priorities,e);
}
}Junit测试类:import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;public class TestExpressionUtil {
Map<String,Integer> priorities = null;
Map<String,Double> dict = null;
Map<String,Double> realDict = null;
@Before
public void setUp() throws Exception {
priorities = new HashMap<String,Integer>();
priorities.put("(", 9);
priorities.put(")", 9);
priorities.put("/", 8);
priorities.put("*", 8);
priorities.put("+", 7);
priorities.put("-", 7);
dict = new HashMap<String,Double>();
dict.put("a", 2.0);
dict.put("b", 1.0);
dict.put("c", 5.0);
dict.put("d", 3.0);
dict.put("e", 1.0);
dict.put("f", 4.0);
dict.put("g", 10.0);
dict.put("h", 5.0);
dict.put("i", 6.0);
realDict = new HashMap<String,Double>();
realDict.put("{a}", 1.0);
realDict.put("{b}", 2.0);
realDict.put("{c}", 3.0);
realDict.put("{d}", 4.0);
realDict.put("{e}", 5.0);
realDict.put("{f}", 6.0);
realDict.put("{g}", 7.0);
realDict.put("{h}", 8.0);
realDict.put("{i}", 9.0);
} @After
public void tearDown() throws Exception {
} @Test
public void testGetPostfixExp() {
String expression = "A+B*(C+D)-E/F";//"(a-b)*c+d-e/f";
String output = "ABCD+*+EF/-";//"ab-c*d+ef/-";
assertEquals(
output,
new ExpressionUtil().getPostfixExp(
expression,
priorities
)
);
}
@Test
public void testGetValueByPostfix(){
String postfix ="ab-c*d+ef/-"; //(a-b)*c+d-e/f = (2-1)*5+3-1/4 = 7.75
//String postfix ="badf+*+ih/-"; //1234+*+65/- = 13.8
assertEquals(
new Double(7.75),
new ExpressionUtil().getValueByPostfix(
postfix,
dict,
priorities)
);
} @Test
public void testGetValueByExpression(){
String expression = "a+b+c+d*(g-f)";// 2+1+5+3*(10-4)
assertEquals(
new Double(26.0),
new ExpressionUtil().getValueByExpression(
expression,
dict,
priorities)
);
}
@Test
public void testGetValueByExpressionX(){
//String expression = "{a}+{b}+{c}+{d}*({f}-{e})";// 1+2+3+4*(6-5) =10.0
String expression = "({c}-{a}+{b})*({e}-{d})+{f}-{i}/{c}"; //(3-1+2)*(5-4)+6-9/3 =7
assertEquals(
new Double(7.0),
new ExpressionUtil().getValueByExpression(
expression,
realDict,
priorities,
new String[]{"{","}"})
);
}
}
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class ScriptEngineTest { public static void main(String[] args) {
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine se = sem.getEngineByName("js");
try {
System.out.println(se.eval("1+2*(3+4)").toString());
} catch (ScriptException e) {
e.printStackTrace();
}
}}学习了!!
http://topic.csdn.net/u/20081011/11/c69b34f6-7605-44a4-918b-a4bed78e8654.html也可以不自己解析,使用动态脚本库,JDK 6 的 JavaScript 引擎是不错的选择,不过只有 JDK 6 及以上版本才有。当然了,还有很多其他开源的脚本库,比如:Rhino, BeanShell, Janino。其中以 Janino 最为高效,直接使用 JVM 运行。
这个我刚拿去运行了下,可是那个test那几个注解不知道放哪些包,老是报错!最后我直接改为main测试了
结果:String expression = "({c}-{a}+{b})*({e}-{d})+{f}-{i}/{c}"; //(3-1+2)*(5-4)+6-9/3 =7我把(3-1+2)*(5-4)+6-9/3 =7放上去运行会报错空指针错误的!
2个stack,一个放数字,一个放运算符。
然后一个一个取出来,判断运算的优先级,优先级大的就运算,否则继续压栈