Java Reference
In-Depth Information
// Step 3: Display the area
}
}
The program needs to read the radius entered by the user from the keyboard. This raises
two important issues:
Reading the radius.
Storing the radius in the program.
Let's address the second issue first. In order to store the radius, the program needs to
declare a symbol called a variable. A variable represents a value stored in the computer's
memory.
Rather than using x and y as variable names, choose descriptive names: in this case, radius
for radius, and area for area. To let the compiler know what radius and area are, specify their
data types. That is the kind of the data stored in a variable, whether integer, floating-point
number , or something else. This is known as declaring variables. Java provides simple data types
for representing integers, floating-point numbers (i.e., numbers with a decimal point), characters,
and Boolean types. These types are known as primitive data types or fundamental types.
Declare radius and area as double-precision floating-point numbers. The program can
be expanded as follows:
variable
descriptive names
data type
declare variables
floating-point number
primitive data types
public class ComputeArea {
public static void main(String[] args) {
double radius;
double area;
// Step 1: Read in radius
// Step 2: Compute area
// Step 3: Display the area
}
}
The program declares radius and area as variables. The reserved word double indicates
that radius and area are double-precision floating-point values stored in the computer.
The first step is to prompt the user to designate the circle's radius . You will learn how to
prompt the user for information shortly. For now, to learn how variables work, you can assign
a fixed value to radius in the program as you write the code; later, you'll modify the pro-
gram to prompt the user for this value.
The second step is to compute area by assigning the result of the expression radius *
radius * 3.14159 to area .
In the final step, the program will display the value of area on the console by using the
System.out.println method.
Listing 2.1 shows the complete program, and a sample run of the program is shown in
Figure 2.1.
L ISTING 2.1 ComputeArea.java
1 public class ComputeArea {
2
public static void main(String[] args) {
3
double radius; // Declare radius
4
double area; // Declare area
5
6 // Assign a radius
7 radius = 20 ; // radius is now 20
 
Search WWH ::




Custom Search