请帮我如何将字符串更改为一组命令行。请考虑以下代码:
public class TestStringCommand{
public static void main(String[] args) {
System.out.println("Change String to Command");
int a , b, c;
String S = "a =1 ; b =2; c = a + b;";
//How to change S into a set of command lines
// c will be 3
}
}
答案 0 :(得分:0)
一般来说,如果它只是那些变量而只是添加,你可以摆脱所有的空格并打开字符。
int a, b, c; Pattern integer = Pattern.compile("-?\\d+"); //fields
主:
String input = ... ;
String statements = input.replaceAll("\\s+",""); //remove the white space
int next_statement_start, current_stmnt_start = 0;
while ( ! statements.isEmpty() ) {
//^ while we have more statements to process
next_statement_start = statements.indexOf(';') + 1;
String statement = statments.substr(current_stmnt_start, next_statement_start);
processStatement(statement);
current_stmnt_start = next_statement_start;
next_statement_start = statements.indexOf(';', next_statement_start) + 1
}
processStatement:
String[] parts = stmnt.split("=");
if ( parts.length != 2) throw new IllegalArgumentException(...);
int val = evaluateExpression(parts[1].substr(0, parts[1].length()-1)); //remove the ';'
setVar(parts[0], val);
SETVAR:
switch ( var ) {
case "a": a = val; break;
case "b": b = val; break;
...
default:
throw new IllegalArgumentException(...);
}
getVar:
switch ( var ) {
case "a": return a;
case "b": return b;
...
default:
throw new IllegalArgumentException (...)
}
evaluateExpression:
if (expr.isEmpty()) throw new ...;
int sum = 0; Matcher m = integer.matcher("");
for (String part : expr.split("+")) {
if (m.reset(part).matches()) {
sum += Integer.parseInt(part);
} else {
sum += getVar(part);
}
}
return sum;
我甚至没有尝试编译上面的代码,但这是个主意。您也可以使用reflection虽然功能强大,但通常不是正确的方法。
或者这就是你想要的? https://en.wikipedia.org/wiki/Recursive_descent_parser
或者这是你真正需要的吗?https://docs.oracle.com/javase/tutorial/essential/environment/properties.html