CSci 101: Introduction to Programming
A Calculator Applet
Java 1.2
This is a simple four-function calculator. It can
add, subtract, multiply, and divide integers. There
are a couple of blank keys. For instance, there's no
decimal point in the usual place on the keyboard since
this calculator doesn't do decimal fractions. There's
also no reciprocal button. Division is "integer division"
which forgets any fractional part of the quotient.
There's no precedence (order) of operations on this
calculator. So if you enter
22 - 6 / 2 =,
you'll get as your final answer 8, which is
(22 - 6)/2, not 22 - (6/2).
The "+/-" key negates the number being displayed.
It can't be used to enter negative numbers.
There is no check for overflow. That is, if you
add two large positive integers together, the result
will be negative. But there is a check for division
by 0. That gives an "Error" that must be cleared by
pressing the C key.
Source. The source for this applet is not available, but
a skeleton for it is Calculator0.java.
The init method for the applet is complete. It sets
up the buttons and the output field that displays the
current number. The actionPerformed method is not
complete. The missing parts have to be filled in for
the calculator to work properly. There are a couple of
private helping methods included. The displayCurrentValue
method places the current value in the output field for
viewing by the user. The computeLastOperation
method actually performs the computations. Here's what the
skeleton calculator looks like. It can do very little, namely,
division of one-digit numbers by one-digit numbers. Also, it
can negate.
Copy the Calculator0.java
file and fix up the missing parts to make it work like above.
Later, you may want to add features to it. For instance,
- Change it from an integer calculator without decimal
fractions into a calculator with fractions. After that, you'll
want to implement some other operations, like reciprocals
and square roots.
- Change the appearance of the calculator. For instance,
different colors.
Also,you can use
images for the keys instead of just characters.
- Fix up the "+/-" key so it can be used to enter negative numbers.
- Improve the output field so that numbers are displayed right
justified instead of left justified.
- Add precedence and/or parentheses.
- Add a feature to the calculator so that the user can enter
numbers by typing them instead of clicking on the keys with the mouse.
- Add memory buttons.
- Put the calculator in a frame outside the web page instead of
on the web page.
- A another window to act as a paper tape that records the
computations for a record.
- Add other functions and features as you like.
- You could even make a designable calculator.
Let subtags in the applet tag on the html page specify whether it's
a four-function calculator, a scientific calculator, or whatever.
Better, let the user reconfigure it.
Anyway, have fun.
Home
D. Joyce
Clark University
April 2002