如何替换方程中的字符值

时间:2016-10-01 06:52:34

标签: java string equations

我有一个等式a + b-c * d。我正在从不同的文件中读取a,b,c,d的值,我将它们存储在一个双数组中。

如何用数组中的数值替换a / b / c / d? 我试过这个,

String l2; //getting the equation string in this from other part of the code. 
//assume a+b-c*d

Double[] secondOperators = new Double[4];
public String getSecondString()
{ 
    l2 = l2.replace("a",toString(secondOperators[0]));
    l2 = l2.replace("b",toString(secondOperators[1]));
    l2 = l2.replace("c",toString(secondOperators[2]));
    l2 = l2.replace("d",toString(secondOperators[3]));  
    return l2;      
}

结果是编译时错误

错误:类Object中的toString方法无法应用于给定类型;

l2 = l2.replace("a",toString(secondOperators[0]));
                        ^

必需:没有参数

发现:双重

原因:实际和正式的参数列表长度不同

1 个答案:

答案 0 :(得分:3)

使用String.valueOf(secondOperators[0])代替toString(secondOperators[0])

编辑:

public static String getSecondString()
{ 
    String l2="a+b-c*d";
    Double[] secondOperators = {22.03,334.34,34.57,231.98};
    l2 = l2.replace("a",String.valueOf(secondOperators[0]));
    l2 = l2.replace("b",String.valueOf(secondOperators[1]));
    l2 = l2.replace("c",String.valueOf(secondOperators[2]));
    l2 = l2.replace("d",String.valueOf(secondOperators[3]));  
    return l2;      
}