FileDocCategorySizeDatePackage
JavaCalc.javaAPI DocExample2402Mon Mar 24 02:02:52 GMT 1997None

JavaCalc

public class JavaCalc extends Applet

Fields Summary
Label
lab
boolean
firstDigit
float
savedValue
String
operator
Constructors Summary
Methods Summary
public booleanaction(java.awt.Event e, java.lang.Object o)

        if (e.target instanceof Button) {
            String s = (String)o;
            if ("0123456789.".indexOf (s) != -1) {  // isDigit
                if (firstDigit) {
                    firstDigit = false;
                    lab.setText (s);
                } else {
                    lab.setText (lab.getText() + s);
                }
            } else {  // isOperator
                if (!firstDigit) {
                    compute (lab.getText());
                    firstDigit = true;
                }
                operator = s;
            }
            return true;
        }
        return false;
    
public voidaddButtons(java.awt.Panel p, java.lang.String labels)

  // Initial operator
           
        int count = labels.length();
        for (int i=0;i<count;i++)
            p.add (new Button (labels.substring(i,i+1)));
    
public voidcompute(java.lang.String s)

        float sValue = new Float (s).floatValue();
        char c = operator.charAt (0);
        switch (c) {
            case '=":   savedValue  = sValue;
                        break;
            case '+":   savedValue += sValue;
                        break;
            case '-":   savedValue -= sValue;
                        break;
            case '*":   savedValue *= sValue;
                        break;
            case '/":   savedValue /= sValue;
                        break;
        }
        lab.setText (String.valueOf(savedValue));
    
public voidinit()

        setLayout (new BorderLayout());
        add ("North", lab = new Label ("0", Label.RIGHT));
        Panel p = new Panel();
        p.setLayout (new GridLayout (4, 4));
        addButtons (p, "789/");
        addButtons (p, "456*");
        addButtons (p, "123-");
        addButtons (p, ".0=+");
        add ("Center", p);