Ok so I am going to try this again. I have a very basic calculator application. I am currently having trouble figuring out how to get my plus() and minus() methods to work. Whenever I run the code, the plus() method is adding currentValue + currentValue. I want it to act like a calculator and add two different integers together. Any suggestions?
digitButton(buttons, 0);
JButton plus = new JButton("+");
plus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
myAccumulator.plus();
updateDisplay();
}
});
buttons.add(plus);
return buttons;
this is where it is getting called.
And this is my class that I wrote with my plus () method.
public class BasicAccumulator implements Accumulator {
private int digit;
private int currentValue;
public void BasicAccumulator(int digit, int currentValue)
{
this.digit = digit;
this.currentValue = currentValue;
}
public void addDigit(int digit)
{
currentValue = currentValue * 10 + digit;
}
public void plus()
{
if (currentValue != 0)
digit = currentValue;
currentValue = currentValue + digit;
}
public void minus()
{
currentValue = currentValue - digit;
}
public void clear()
{
currentValue = 0;
}
public int displayValue()
{
return currentValue;
}
}
Think about it. At the time you press +, you presumably have not yet entered the second number. That is, if your calculator is intended to work like most calculators out there…
Presumably you have the following sequence of events..
For this, I would conceptually store 3 things in the accumulator:
So… Initially,
leftis zero andoperationis nothing (ie ‘clear’).Type in some digits… These are built up in ‘right’.
Press +. Now, you apply any pending operation to
left. In this case the operation is empty, so you just copy the value and clear ‘right’. Then you set the operation to ‘+’You type in more digits, once again building up
right.You hit + again. Now the operation is applied. You add
righttoleftand clearright.etc etc…