Java Reference
In-Depth Information
static final double
CENTIMETERS_PER_INCH = 2.54;
static final int
INCHES_PER_FOOT = 12;
In the preceding sections, we analyzed the problem and determined the formulas to
perform the calculations. We also determined the necessary variables and named
constants. We can now expand the algorithm given in the section Problem Analysis
and Algorithm Design to solve the problem given at the beginning of this program-
ming example (converting feet and inches to centimeters).
1. Prompt the user for the input. (Without a prompt line, the user will
stare at a blank screen and not know what to do.)
2. Get
feet
.
3. Prompt the user to enter a value for
inches
.
4. Get
inches
.
5. Echo the input by outputting what the program read as input.
(Without this step, after the program has executed, you will not
know what the input was.)
6. Find the length in inches.
7. Output the length in inches.
8. Convert the length to centimeters.
9. Output the length in centimeters.
MAIN
ALGORITHM
Now that the problem has been analyzed and the algorithm has been designed, the
next step is to translate the algorithm into Java code. Because this is the first complete
Java program you are writing, let's review the necessary steps in sequence.
The program will begin with comments that document its purpose and functionality.
Because there is both input to this program (the length in feet and inches) and output
(the equivalent length in centimeters), you will use the system resources for input/
output. In other words, the program will use input statements to get the data into the
program and output statements to print the results. Because the data will be entered
from the keyboard, the program must import the
class
Scanner
from the package
java.util
. Thus, the first statement of the program, following the comments
described previously, will be the
import
statement to import the
class
Scanner
from the package
java.util
.
This program requires two types of memory locations for data manipulation: named
constants and variables. Recall that named constants are usually placed before the
method
main
so that they can be used throughout the program.
This program has only one class, which contains the method
main
. The method
main
will contain all of the programming instructions in its body. In addition, the
program needs variables to manipulate the data; these variables will be declared in
PUTTING IT
TOGETHER
Search WWH ::
Custom Search