String f="30*12*0.3+5", 如何让他动态执行,f的值不固定

andy0618 2008-10-11 11:51:54
String f="30*12*0.3+5", 如何让他动态执行,f的值不固定
...全文
988 28 打赏 收藏 转发到动态 举报
写回复
用AI写文章
28 条回复
切换为时间正序
请发表友善的回复…
发表回复
ilce11 2008-10-11
  • 打赏
  • 举报
回复
我觉得二楼的说的对,,
你都用""了,表示是字符串,怎么计算啊。。
直接得出f的值为30*12*0.3+5
ilce11 2008-10-11
  • 打赏
  • 举报
回复
我觉得二楼的说的对,,
你都用""了,表示是字符串,怎么计算啊。。
直接得出f的值为30*12*0.3+5
zz2617436 2008-10-11
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 ZangXT 的回复:]
Java code
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Test{
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();

ScriptEngine engine = manager.getEngineByName("javascript");
try {
Double d = (Double) engine.eval("10*5+9…
[/Quote]

UP,UP,UP
ZangXT 2008-10-11
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 andy0618 的回复:]

to 做好自己的事情

javax.script.ScriptEngine
包在哪里
[/Quote]
java6自带的。
没有的话参考6楼的方法,动态编译。
andy0618 2008-10-11
  • 打赏
  • 举报
回复

to 做好自己的事情

javax.script.ScriptEngine
包在哪里
zjchxj 2008-10-11
  • 打赏
  • 举报
回复
三楼很强
ZangXT 2008-10-11
  • 打赏
  • 举报
回复
如果jdk是1.6以前的版本,参考
http://blog.csdn.net/axman/archive/2004/11/05/167002.aspx
ZangXT 2008-10-11
  • 打赏
  • 举报
回复
Double d = (Double) engine.eval("10*5+9-25/2");
eval中直接使用你的字符串表达式即可。
zhj92lxs 2008-10-11
  • 打赏
  • 举报
回复
按不同的运算符合拆串,然后计算,不知道还有没有别的方法
ZangXT 2008-10-11
  • 打赏
  • 举报
回复

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Test{
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();

ScriptEngine engine = manager.getEngineByName("javascript");
try {
Double d = (Double) engine.eval("10*5+9-25/2");
System.out.println(d);
} catch (ScriptException ex) {

}

}
}



使用jdk1.6
andy0618 2008-10-11
  • 打赏
  • 举报
回复
String f="30*12*0.3+5",

这个计算公式是一个字符串,如何计算这个字符串的值

zhj92lxs 2008-10-11
  • 打赏
  • 举报
回复
什么意思
valen_jia 2008-10-11
  • 打赏
  • 举报
回复
用EVAL函数
fosjos 2008-10-11
  • 打赏
  • 举报
回复
[Quote=引用 23 楼 ZangXT 的回复:]
表达式分析就用编译原理上的那堆东西吧。
[/Quote]
beanshell能把局部变量和类也整合到一起
也许真像ls说的“不是常人能够研究”

其实,我也只是想知道beanshell用到了java的什么特殊机制
ZangXT 2008-10-11
  • 打赏
  • 举报
回复
贴一个递归下降解析器的例子,来自The Art of Java一书。


/*
This module contains the recursive descent
parser that does not use variables.
*/

// Exception class for parser errors.
class ParserException extends Exception {
String errStr; // describes the error

public ParserException(String str) {
errStr = str;
}

public String toString() {
return errStr;
}
}

class Parser {
// These are the token types.
final int NONE = 0;
final int DELIMITER = 1;
final int VARIABLE = 2;
final int NUMBER = 3;

// These are the types of syntax errors.
final int SYNTAX = 0;
final int UNBALPARENS = 1;
final int NOEXP = 2;
final int DIVBYZERO = 3;

// This token indicates end-of-expression.
final String EOE = "\0";

private String exp; // refers to expression string
private int expIdx; // current index into the expression
private String token; // holds current token
private int tokType; // holds token's type

// Parser entry point.
public double evaluate(String expstr) throws ParserException
{
double result;
exp = expstr;
expIdx = 0;

getToken();
if(token.equals(EOE))
handleErr(NOEXP); // no expression present

// Parse and evaluate the expression.
result = evalExp2();

if(!token.equals(EOE)) // last token must be EOE
handleErr(SYNTAX);

return result;
}

// Add or subtract two terms.
private double evalExp2() throws ParserException
{
char op;
double result;
double partialResult;

result = evalExp3();

while((op = token.charAt(0)) == '+' || op == '-') {
getToken();
partialResult = evalExp3();
switch(op) {
case '-':
result = result - partialResult;
break;
case '+':
result = result + partialResult;
break;
}
}
return result;
}

// Multiply or divide two factors.
private double evalExp3() throws ParserException
{
char op;
double result;
double partialResult;

result = evalExp4();

while((op = token.charAt(0)) == '*' ||
op == '/' || op == '%') {
getToken();
partialResult = evalExp4();
switch(op) {
case '*':
result = result * partialResult;
break;
case '/':
if(partialResult == 0.0)
handleErr(DIVBYZERO);
result = result / partialResult;
break;
case '%':
if(partialResult == 0.0)
handleErr(DIVBYZERO);
result = result % partialResult;
break;
}
}
return result;
}

// Process an exponent.
private double evalExp4() throws ParserException
{
double result;
double partialResult;
double ex;
int t;

result = evalExp5();

if(token.equals("^")) {
getToken();
partialResult = evalExp4();
ex = result;
if(partialResult == 0.0) {
result = 1.0;
} else
for(t=(int)partialResult-1; t > 0; t--)
result = result * ex;
}
return result;
}

// Evaluate a unary + or -.
private double evalExp5() throws ParserException
{
double result;
String op;

op = "";
if((tokType == DELIMITER) &&
token.equals("+") || token.equals("-")) {
op = token;
getToken();

}
result = evalExp6();

if(op.equals("-")) result = -result;

return result;
}

// Process a parenthesized expression.
private double evalExp6() throws ParserException
{
double result;

if(token.equals("(")) {
getToken();
result = evalExp2();
if(!token.equals(")"))
handleErr(UNBALPARENS);
getToken();
}
else result = atom();

return result;
}

// Get the value of a number.
private double atom() throws ParserException
{
double result = 0.0;

switch(tokType) {
case NUMBER:
try {
result = Double.parseDouble(token);
} catch (NumberFormatException exc) {
handleErr(SYNTAX);
}
getToken();
break;
default:
handleErr(SYNTAX);
break;
}
return result;
}

// Handle an error.
private void handleErr(int error) throws ParserException
{
String[] err = {
"Syntax Error",
"Unbalanced Parentheses",
"No Expression Present",
"Division by Zero"
};

throw new ParserException(err[error]);
}

// Obtain the next token.
private void getToken()
{
tokType = NONE;
token = "";

// Check for end of expression.
if(expIdx == exp.length()) {
token = EOE;
return;
}

// Skip over white space.
while(expIdx < exp.length() &&
Character.isWhitespace(exp.charAt(expIdx))) ++expIdx;

// Trailing whitespace ends expression.
if(expIdx == exp.length()) {
token = EOE;
return;
}

if(isDelim(exp.charAt(expIdx))) { // is operator
token += exp.charAt(expIdx);
expIdx++;
tokType = DELIMITER;
}
else if(Character.isLetter(exp.charAt(expIdx))) { // is variable
while(!isDelim(exp.charAt(expIdx))) {
token += exp.charAt(expIdx);
expIdx++;
if(expIdx >= exp.length()) break;
}
tokType = VARIABLE;
}
else if(Character.isDigit(exp.charAt(expIdx))) { // is number
while(!isDelim(exp.charAt(expIdx))) {
token += exp.charAt(expIdx);
expIdx++;
if(expIdx >= exp.length()) break;
}
tokType = NUMBER;
}
else { // unknown character terminates expression
token = EOE;
return;
}
}

// Return true if c is a delimiter.
private boolean isDelim(char c)
{
if((" +-/*%^=()".indexOf(c) != -1))
return true;
return false;
}

}


sunyujia 2008-10-11
  • 打赏
  • 举报
回复
我感觉像beanshell Groovy js引擎这类东西的原理和实现都不是常人能够研究的。。。。
呵呵!不研究也罢。
ZangXT 2008-10-11
  • 打赏
  • 举报
回复
表达式分析就用编译原理上的那堆东西吧。
fosjos 2008-10-11
  • 打赏
  • 举报
回复
以前用过多次,就是没有深究其原理,偶也是懒人一个,没这个精力
fosjos 2008-10-11
  • 打赏
  • 举报
回复
借人气一问,

楼上有没有哪位知道beanshell是如何实现eval的?
sunyujia 2008-10-11
  • 打赏
  • 举报
回复
呵呵,攒一个。
加载更多回复(8)

81,094

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧