import javax.swing.*; import java.awt.*; import java.awt.event.*; // the calculator takes care of the actual calcualtions, and stores the // current number this class extends the JLabel so it can also serve as // a display of the current number public class Calculator extends JLabel { // the state which we are in private CalculatorState state; // the current value we are using private double value; // the saved value if we are doing an operator private double saved; // whether or not new digits are being added after the dot private boolean dot; // the amount of places after the dot to add private int place; public Calculator() { // clear should initialize us to 0, so just call that clear(); } // called to clear out the calculator public void clear() { // set all the default values value = 0.0; saved = 0.0; dot = false; place = 0; state = CalculatorState.DEFAULT; // update the display update(); } // update the display with the current value public void update() { // convert the value to a string String stringValue = Double.toString(value); // since we are a JLabel, we have a setText function, just call it setText(stringValue); } // called when the user pushes one of the digit buttons public void addDigit(int digit) { // if the state is done, reset things first if (state == CalculatorState.DONE) { clear(); } // if there has not been a dot yet if (!dot) { // add this digit to the end, but multiplying the current value // by ten and then adding it in value = value * 10 + digit; } else { // add this digit in the next decimal place available value = value + digit / (Math.pow(10.0, place)); place++; } // update the display update(); } // called when equals gets pushed public void equals() { // apply the operator depending on our state switch (state) { case DEFAULT: // do nothing! break; case ADDING: value = saved + value; break; case SUBTRACTING: value = saved - value; break; case MULTIPLYING: value = saved * value; break; case DIVIDING: value = saved / value; break; } // update to the new value update(); // go to the DONE state state = CalculatorState.DONE; } // called when the dot button is pushed public void setDot() { // if we already hada a dot, this is an error! if (dot) { throw new IllegalStateException("Can't have two decimal points"); } // set the dot dot = true; place = 1; } // called when an operator button is pushed public void setOperator(char operator) { // save the current value; saved = value; // reset value to read value = 0.0; dot = false; place = 0; // remember the operator so we can apply it later switch (operator) { case '+': state = CalculatorState.ADDING; break; case '-': state = CalculatorState.SUBTRACTING; break; case '*': state = CalculatorState.MULTIPLYING; break; case '/': state = CalculatorState.DIVIDING; break; default: throw new IllegalArgumentException("Invalid Operator"); } } // called for the square root operation public void sqrt() { value = Math.sqrt(value); update(); } }