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 data stored in a variable, whether integer, real number, or some-
thing else. This is known as
declaring variables.
Java provides simple data types for represent-
ing integers, real numbers, characters, and Boolean types. These types are known as
primitive
data types
or
fundamental types.
Real numbers (i.e., numbers with a decimal point) are represented using a method known
as
floating-point
in computers. So, the real numbers are also called
floating-point numbers
. In
Java, you can use the keyword
double
to declare a floating-point variable. Declare
radius
and
area
as
double
. The program can be expanded as follows:
■
variable
descriptive names
data type
declare variables
primitive data types
floating-point number
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 floating-point values stored in the computer.
The first step is to prompt the user to designate the circle's
radius
. You will soon learn
how to prompt the user for information. 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 program
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
Search WWH ::
Custom Search