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,

Anyway, have fun.


Home

D. Joyce
Clark University
April 2002