Pocket Calculator
import java.awt.*;
public class Pocket extends Frame
{
TextField t;
Button h[] = new Button[16];
int accumulator = 0;
boolean start = true;
int op = 0;
public Pocket ()
{
setTitle("Pocket Calculator");
add("North", t = new TextField());
t.setEditable(false);
Panel p = new Panel();
p.setLayout(new GridLayout(4,4));
for (int i=0 ; i < 10 ; i++)
p.add(h[i] = new Button(String.valueOf(i)));
p.add(h[10] = new Button("+"));
p.add(h[11] = new Button("-"));
p.add(h[12] = new Button("="));
p.add(h[13] = new Button("+/-"));
p.add(h[14] = new Button("*"));
p.add(h[15] = new Button("/"));
add("Center",p);
}
public boolean action (Event evt, Object obj)
{
int input;
for (int i=0 ; i < 10 ; i++) // A digit button is pressed
{
if (evt.target.equals(h[i]))
{
if (start) { start = false; t.setText(""); }
t.setText(t.getText() + String.valueOf(i));
return super.action(evt, obj);
}
}
if (evt.target.equals(h[13])) // The +/- button is pressed
t.setText(String.valueOf(-Integer.parseInt(t.getText())));
else // Some operation is requested (+,-,*,/,=)
{
for (int i=10 ; i < 16 ; i++)
{
if (evt.target.equals(h[i]))
{
start = true;
if (t.getText().equals("")) input = 0;
else
input = Integer.parseInt(t.getText());
switch (op) {
case 10: accumulator += input; break;
case 11: accumulator -= input; break;
case 14: accumulator *= input; break;
case 15: accumulator /= input; break;
default:
if (t.getText().equals("")) accumulator = 0;
else accumulator = Integer.parseInt(t.getText());
}
op = i;
if (op == 12) t.setText(String.valueOf(accumulator));
}
}
}
return super.action(evt, obj);
}
public static void main (String arg[])
{
Pocket calculator = new Pocket();
calculator.resize(200,300);
calculator.show();
}
}