Java Reference
In-Depth Information
Recall that saving the program before entering any code causes TextPad to
display Java-related color coding as you begin to enter code. It also causes the file
name to display on the title bar, on the Windows taskbar, and in the Selector
window, which provides a visual reference as you enter code. Finally, after the file
is saved once, you can click the Save button on the Standard toolbar to resave the
file to the same folder. TextPad also automatically resaves the file each time the
program is compiled.
Coding the Program
As you have learned, the implementation phase of the development cycle
involves writing the code that translates the design into a program. During
program design, pseudocode was used to outline the logic of the program code
in the Body Mass Index Calculator application (Figure 3-5a on page 135). As
outlined in that pseudocode, the task to be performed is to accept two inputs of
height and weight, convert the input values to metric, calculate body mass index
using a given formula, and then display the BMI value as output. The coding
process starts with entering the beginning program code.
Entering Beginning Code
Similar to the console application program in Chapter 2, the code for the
Body Mass Index Calculator program will include comments, a class header, and
a main() method. The code for the Body Mass Index Calculator also will use an
import statement to import the java.io package. Recall from Chapter 2 that the
java.lang package is the only package imported automatically without an explicit
command; all other packages need an import statement to tell the compiler
where to access the classes, fields, and methods of an existing class in the pack-
age. In this program, the java.io package is imported to provide classes to sup-
port system input and output.
When you use certain methods from the java.io package, you must warn the
compiler that the possibility of errors exists. For instance, a user might not have
authority to open a file, a disk might not be located in the proper disk drive, or
the system might be busy with other input. An easy way to keep the program
from aborting prematurely due to these kinds of errors is to add the code,
throws IOException, to the end of the main() method header. The code, throws
IOException , gives the program a way to acknowledge and handle potential
input or output errors and still compile correctly.
Figure 3-7 on the next page displays the code for the comment header,
import statement, class header, and main() method header used in the Body
Mass Index Calculator program.
Search WWH ::




Custom Search