【问题标题】:How to change S into a set of command lines如何将S变成一组命令行
【发布时间】:2015-09-13 23:49:12
【问题描述】:

请帮助我如何将字符串更改为一组命令行。请考虑以下代码:

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

   }
}

【问题讨论】:

    标签: java string command


    【解决方案1】:

    一般来说,如果只是那些变量和加法,你可以去掉所有的空白并打开字符。

    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
    }
    

    流程声明:

    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);
    

    设置变量:

    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 (...)
    }
    

    评估表达式:

    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

    【讨论】:

      猜你喜欢
      • 2015-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 2021-12-20
      • 2015-01-25
      相关资源
      最近更新 更多