Java Reference
In-Depth Information
T
ABLE
2.1
Methods for
Scanner
Objects
Method
Description
reads an integer of the
byte
type.
nextByte()
reads an integer of the
short
type.
nextShort()
reads an integer of the
int
type.
nextInt()
reads an integer of the
long
type.
nextLong()
reads a number of the
float
type.
nextFloat()
reads a number of the
double
type.
nextDouble()
reads a string that ends before a whitespace character.
next()
reads a line of text (i.e., a string ending with the
Enter
key pressed).
nextLine()
8
// Prompt the user to enter a radius
9 System.out.print(
"Enter a number for radius: "
);
10
read a
double
double
radius =
input.nextDouble();
11
12
// Compute area
13
double
area = radius * radius * 3.14159;
14
15
// Display results
16 System.out.println(
"The area for the circle of radius "
+
17 radius +
" is "
+ area);
18 }
19 }
Enter a number for radius:
The area for the circle of radius 2.5 is 19.6349375
2.5
Enter a number for radius:
The area for the circle of radius 23.0 is 1661.90111
23
The
Scanner
class is in the
java.util
package. It is imported in line 1. Line 6 creates a
Scanner
object.
The statement in line 9 displays a message to prompt the user for input.
System.out.
print
(
"Enter a number for radius: "
);
The
print
method is identical to the
println
method except that
println
moves to the
beginning of the next line after displaying the string, but
print
does not advance to the next
line when completed.
The statement in line 10 reads input from the keyboard.
print
vs.
println
double
radius = input.nextDouble();
After the user enters a number and presses the
Enter
key, the program reads the number
and assigns it to
radius
.