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

このような解析ジョブを実行する最善の方法は、パーサー ジェネレーターを使用することです。ただし、自分でやりたい場合は、いくつかの選択肢があります。この場合、次の方法でも実行できます。

  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 に答える