Please help me with my code. i’m using an arraylist named tempAns, it contain values [2, 9, 2]. i’ve tried adding the last two numbers then replace them with the right answer so the result will be [2, 11]. but somehow, the output was always [9, 11]. it seems like it’s deleting duplicate values.
else if(scan.equals("+"))
{
double num2 = Double.parseDouble(tempAns.get(tempAns.size()-1));
double num1 = Double.parseDouble(tempAns.get(tempAns.size()-2));
double ans = num1 + num2;
String stringAns = Double.toString(ans);
System.out.println("before deleting: " +tempAns + "\n");
tempAns.remove(tempAns.get(tempAns.size()-1));
tempAns.remove(tempAns.get(tempAns.size()-1));
System.out.println("before adding: " +tempAns);
tempAns.add(stringAns);
System.out.println(num1 + " + " +num2+ " = " +ans);
System.out.println("after deleting: " +tempAns + "\n");
}
One thing to consider is that you can consolidate the place where you retrieve num1 and num2 and where you remove them like such:
The previous code fixes the issue you were having and may be easier to follow as you are not trying to keep track of the offset where the items are in the list. This is a bit closer to popping the list off a stack and then pushing it back when you calculate the value.