I am trying to read the sign from the arraylist, then do the expression for the two numbers before it and after it (for example, i-1 * i+1) . However the generated result is always either 5, 6 or 12! I cannot really find where the issue is within the code.
I am using arraylist because it is more dynamic than an array, in a sense that I can delete elements without caring about the length of the 'array'.
String replaceStr = replacer.replace("+", " + ");
I am trying to add space in order to take the whole numbers as an element rather than using charAt which will not allow me to take a number that is more than one digit into the equation.
Double Computing(String equation) {
double result = 0.0;
double multiplResult = 1.0; //
String replacer = equation;
String replaceStr = replacer.replace("+", " + ");
String replaceStr1 = replaceStr.replace("x", " x ");
String replaceStr2 = replaceStr1.replace("-", " - ");
String replaceStr3 = replaceStr2.replace("/", " / ");
String[] items = replaceStr3.split("\\s*");
ArrayList<String> list = new ArrayList<String>((Arrays.asList(items)));
for (int i = 0; i < list.size(); i++ ) {
String NewNum;
if (list.get(i) == "x" || list.get(i) == "/"){
if(list.get(i) == "x") {
NewNum = String.valueOf(Double.parseDouble(list.get(i - 1)) * Double.parseDouble(list.get(i + 1)));
list.set(i, NewNum);
list.remove(i-1);
list.remove(i+1);
}
else if (list.get(i) == "/"){
NewNum = String.valueOf(Double.parseDouble(list.get(i - 1)) / Double.parseDouble(list.get(i + 1)));
list.set(i, NewNum);
list.remove(i-1);
list.remove(i+1);
}
multiplResult *= Double.parseDouble(list.get(0));
}
if (list.get(i) == "+" || list.get(i) == "-"){
if(list.get(i) == "+") {
NewNum = String.valueOf(Double.parseDouble(list.get(i - 1)) + Double.parseDouble(list.get(i + 1)));
list.set(i, NewNum);
list.remove(i-1);
list.remove(i+1);
}
else if (list.get(i) == "-"){
NewNum = String.valueOf(Double.parseDouble(list.get(i - 1)) - Double.parseDouble(list.get(i + 1)));
list.set(i, NewNum);
list.remove(i-1);
list.remove(i+1);
}
multiplResult *= Double.parseDouble(list.get(0));
}
result += multiplResult;
}
return result;
}