2

这是我制作的代码:

public static boolean isOperator(char op){
    if (op == '+' || op == '-'
            || op == '*' || op == '/'
            || op == '^'
            || op == '(' || op == ')'){
        return true;
    }
    return false;
}

public static boolean isOperand(char op){
    String numbers = "0123456789.";
    int a = numbers.indexOf(op);
    return a >= 0;
}
public static void main(String []args){        
    String exp= "15+20+(3.84*25)*(78/3.8)";
    LinkedList a = new LinkedList();

    for (int i = 0; i < exp.length(); i++){
        if (isOperator(exp.charAt(i))){
            a.add(exp.charAt(i));
        } else if (isOperand(exp.charAt(i))){
            int k = i;
            while (k < exp.length()){//I see the length of the number
                if (isOperand(exp.charAt(k))){
                    k++;
                } else {
                    break;
                }
            }
            if (k != exp.length()-1){//if it's not ad the end
                a.add(exp.substring(i, k));
            } else {//if it's at the end I take all the remaining chars of the string
                a.add(exp.substring(i));
            }
            i = k-1;//i must go back since the subtring second parameter is exclusive
        } 
    }
    System.out.println(a);    
}//main

这是输出:

[15, +, 20, +, (, 3.84, *, 25, ), *, (, 78, /, 3.8), )]

这正是我想要的。如您所见,我将操作数和运算符分别放入维护字符串顺序的列表中。有一种更简单的方法吗?

4

2 回答 2

6

有没有办法以更简单的方式做到这一点?

就在这里。使用正则表达式。查看以下代码并尝试为您的输入运行它。

public static void main(String[] args) 
{
    String exp = "15+20+(3.84*25)*(78/3.8)";
    String regex = "(\\d+\\.\\d+)|(\\d+)|([+-/*///^])|([/(/)])";

    Matcher m = Pattern.compile(regex).matcher(exp);

    LinkedList list = new LinkedList();

    while (m.find()) {
        list.add(m.group());
    }

    System.out.println(list);
}

我上面使用的正则表达式的解释:

“(\d+\.\d+)|(\d+)|([+-/*///^])|([/(/)])”

(双)或(整数)或(算术运算符)或(左/右括号)

于 2012-10-13T10:07:07.067 回答
2

进行此类解析工作的最佳方法是使用 Parser 生成器。但是,如果你想自己做,你有很多选择。在这种情况下,您也可以这样做:

  public static void main(String[] args) throws Exception{ 
      String exp = "15+20+(3.84*25)*(78/3.8)";
      LinkedList<String> a = new LinkedList<String>();

      StringTokenizer st = new StringTokenizer(exp, "+*/-()", true);
      while(st.hasMoreTokens())
          a.add(st.nextToken());
    } 
于 2012-10-13T10:17:41.580 回答