最后我解决了这个问题,下面的类:
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/**
*
* @author Aniruddha Sarkar(c)
* [email protected]
*/
public class ExpSolver {
String[] regx;
public ExpSolver() {
regx=new String[]{
"Math.abs", // the absolute value of a
"Math.acos", // arc cosine of a
"Math.asin", // arc sine of a
"Math.atan", // arc tangent of a
"Math.atan2", // arc tangent of a/b
"Math.ceil", // integer closest to a and not less than a
"Math.cos", // cosine of a
"Math.exp", // exponent of a ("Math.E to the power a)
"Math.floor", // integer closest to a, not greater than a
"Math.log", // log of a base e
"Math.max", // the maximum of a and b
"Math.min", // the minimum of a and b
"Math.pow", // a to the power b
"Math.random", // pseudorandom number 0 to 1 (see examples)
"Math.round", // integer closest to a (see rounding examples)
"Math.sin", // sine of a
"Math.sqrt", // square root of a
"Math.tan" // tangent of a
};
}
public String solve(String s,String p){
for(String str:regx){
s=s.replaceAll(str.substring(str.indexOf(".")+1), str);
}
int x;
while(s!=null){
x=s.indexOf('^');
if(x!=-1){
StringBuilder xa=new StringBuilder();
for(int i=x-1;i>=0;i--){
char k=s.charAt(i);
if(Character.isDigit(k)||k=='.'||k=='E'){
xa.append(k);
}
else if(i>0)
if(s.charAt(i-1)=='E'){
xa.append(k);
}
else{
if(k=='-'){
if(i>0){
int kdx=i-1;
if(kdx>0){
char kt=s.charAt(kdx);
if(!(Character.isDigit(kt)||kt=='.')){
xa.append(k);
}
}
}
else{
xa.append(k);
}
}
break;
}
}
xa.reverse();
StringBuilder xb=new StringBuilder();
xb.append(s.charAt(x+1));
for(int i=x+2;i<s.length();i++){
char k=s.charAt(i);
if(Character.isDigit(k)||k=='.'||k=='E'||s.charAt(i-1)=='E'){
xb.append(k);
}
else{
break;
}
}
double a=Double.parseDouble(xa.toString()),b=Double.parseDouble(xb.toString());
double r=Math.pow(a,b);
s=s.substring(0,x-xa.length())+((int)r==r?(int)r:r)+s.substring(x+xb.length()+1,s.length());
continue;
}
break;
}
try {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
engine.put("x", Double.parseDouble(p));
return round(Double.parseDouble(engine.eval(s).toString()))+"";
} catch (ScriptException ex) {
Logger.getLogger(ExpSolver.class.getName()).log(Level.SEVERE, null, ex);
}
return "0";
}
public static void main(String args[]){
System.out.println(new ExpSolver().solve(new java.util.Scanner(System.in).nextLine(),"25"));
}
public static float round(double x){
return ((float)Math.rint((x-0.05)*100))/100;
}
}
这很酷... – 2014-09-25 17:20:57