I want to do an arithmetic operation on data stored in an Array.
User may choose random column and random operation on them.
like,
String DataTmp[10][3] = ...;
String strCalc = "Float.parseFloat(DataTmp[i][0]) + Float.parseFloat(DataTmp[i][2]) * Float.parseFloat(DataTmp[i][1])";
Is there any way to achieve this?
Edited: The calculation mentioned above is for example. It is not the fixed calculation. It may change anyway like,
String strCalc = "Float.parseFloat(DataTmp[i][1]) / Float.parseFloat(DataTmp[i][2])";
or
String strCalc = "(Float.parseFloat(DataTmp[i][2]) - Float.parseFloat(DataTmp[i][1])) / Float.parseFloat(DataTmp[i][1])";
So i can't just do that dynamic calculate. I need to execute the expression inside the String.
Further Edited:
User have a textbox to enter the calculation.
So, the user will enter something like "(field 1 - field 3)/field 2" or anything as they wish.
I need to take the corresponding value for fields from array and apply the operation (+,-,*,/) as per the user's selection.
Everything in this expression is dynamic, including the field order and operations.
Solution Implemented:
here is the long possible solution i reached. add improvements if you've any.
i didn't implement the hierarchy of calculation based on parenthesis.
strCalc = strCalc.replace("(", "");
strCalc = strCalc.replace(")", "");
List<String> calcList = new ArrayList<String>(Arrays.asList(strCalc
.split(" ")));
showInfo("List Size : " + calcList.size());
// Doing multiplication and division first
for (int i = 0; i < calcList.size(); i++) {
String curStr = calcList.get(i);
if (curStr.compareTo("*") == 0) {
float val1 = Float.parseFloat(calcList.get(i - 1));
float val2 = Float.parseFloat(calcList.get(i + 1));
calcList.remove(i - 1);
calcList.remove(i - 1);
calcList.remove(i - 1);
float result = val1 * val2;
calcList.add(i - 1, "" + result);
i--;
continue;
}
if (curStr.compareTo("/") == 0) {
float val1 = Float.parseFloat(calcList.get(i - 1));
float val2 = Float.parseFloat(calcList.get(i + 1));
calcList.remove(i - 1);
calcList.remove(i - 1);
calcList.remove(i - 1);
float result = val1 / val2;
calcList.add(i - 1, "" + result);
i--;
continue;
}
}
// Doing addition and subtraction next
for (int i = 0; i < calcList.size(); i++) {
String curStr = calcList.get(i);
if (curStr.compareTo("+") == 0) {
float val1 = Float.parseFloat(calcList.get(i - 1));
float val2 = Float.parseFloat(calcList.get(i + 1));
calcList.remove(i - 1);
calcList.remove(i - 1);
calcList.remove(i - 1);
float result = val1 + val2;
calcList.add(i - 1, "" + result);
i--;
continue;
}
if (curStr.compareTo("-") == 0) {
float val1 = Float.parseFloat(calcList.get(i - 1));
float val2 = Float.parseFloat(calcList.get(i + 1));
calcList.remove(i - 1);
calcList.remove(i - 1);
calcList.remove(i - 1);
float result = val1 - val2;
calcList.add(i - 1, "" + result);
i--;
continue;
}
}
return calcList.get(0);