Back to Applets page
Click in the boxes below, select all and copy to grab the applet
HTML listing:
<html> <head> <title>A simple Java Calculator</title> </head> <body bgcolor=white> <applet codebase="classes" code="calculator.class" height="150" width="300"> </applet> </body> </html>
Applet listing:
import java.awt.*; import java.applet.*; public class calculator extends Applet { TextField display; int saveNum = 0; int memNum = 0; char op = '='; char lastOp = '='; boolean newNum = true; public void init() { setBackground(Color.white); display = new TextField("0",6); display.setEditable(false); add(display); Panel p = new Panel(); p.setLayout(new GridLayout(5, 4)); for (int i = 1; i <= 9; i++) { p.add(new Button("" + i)); if (i==3) p.add(new Button("+")); if (i==6) p.add(new Button("-")); } p.add(new Button("*")); p.add(new Button("%")); p.add(new Button("0")); p.add(new Button("±")); p.add(new Button("/")); p.add(new Button("M")); p.add(new Button("RM")); p.add(new Button("C")); p.add(new Button("=")); add(p); } public boolean action(Event evt, Object arg) { if (arg instanceof String) { String s = (String) arg; if (s.charAt(0) >= '0' && s.charAt(0) <= '9') { if (newNum) display.setText(s); else display.setText(display.getText() + s); newNum = false; } else { if (s.charAt(0) == '-' && newNum) { display.setText("-"); newNum = false; } else { op = s.charAt(0); calc (Integer.parseInt(display.getText())); newNum = true; } lastOp = op; } return true; } return super.action(evt, arg); } public void calc(int n) { switch (op) { case '+': case '-': case '*': case '/': case '%': saveNum = n; return; } if (op == '=') op = lastOp; switch (op) { case '+': saveNum += n; break; case '-': saveNum -= n; break; case '*': saveNum *= n; break; case '/': saveNum /= n; break; case '%': saveNum %= n; break; case 'M': memNum = n; saveNum = n; break; case 'R': saveNum = memNum; break; case 'C': saveNum = 0; break; case '±': saveNum = -n; break; } display.setText("" + saveNum); } }