Easy Code for Java Script Circle⁄Sphere Calculator
In this article I'll show you how to use to Java Script to create a Circle ⁄ Sphere calculator.
With this calculator, the user inputs the radius of a circle or sphere, and the calculator will return
the area and circumference (if a circle) or the surface area and volume (if a sphere). I'll explain
in detail so that you can learn Java Script and modify the code for your own purposes.
I have programmed many Java Script calculators and discovered that, the process for coding any
calculator can be broken down into a step-by-step procedure. Shown below are the steps to build a calculator.
1. Acquire the formula
2. Determine the inputs and outputs
3. Design the html form
4. Write the Java Script to process the form
5. Display the results of the calculation
6. Provide code to handle errors
Note that in step 4 you write the Java Script to process the form, which would include displaying
the results, but I listed displaying the results in step 5. The reason for that is that the output
usually needs to be formatted and this requires a little additional code. The same thing with step
6. You can't rely on the user to enter proper inputs into the form, in step 6 we need to ad code to
validate the input data.
Step 1: Circle and Sphere Formula
Shown below are the formulas we'll use for the Circle ⁄ Sphere calculator:
circle circumference = 2 * Pi * r
circle area = pi * r²
sphere surface area = 4 * pi * r³
sphere volume = 4⁄3 (pi * r³)
Step 2: Determine the Inputs and Outputs
As stated at the beginning of this article, the user will input the radius of a circle or sphere,
and the calculator will return the area and circumference (if a circle) or the surface area and
volume (if a sphere). Those are the mathematical inputs and outputs, but we have several other
inputs and outputs to consider.
We could complicate the heck out of this calculator and get involved in the units and unit conversions.
But the fact of the matter is, these circle and sphere formulas don't care about the units,
that is, the units in are the units out. We could design the calculator to perform units
conversions (e.g. inches to feet or yards to meters) but to keep this example simple, I'm
just going to ignore the units.