Java Reference
In-Depth Information
SR 2.34
Assuming
result
is a
float
variable that contains the value 27.32 and
value
is an
int
variable that contains the
value
15, what are the val-
ues of each of the variables after the following assignment statement is
executed? Explain.
value = (
int
) result;
SR 2.35
Given the following declarations, what result is stored by each of the
following assignment statements.
int
iResult, num1 = 17, num2 = 5;
double
fResult, val1 = 12.0, val2 = 2.34;
a.
iResult = num1 / num2;
b.
fResult = num1 / num2;
c.
fResult = val1 / num2;
d.
fResult = (
double
) num1 / num2;
e.
iResult = (
int
) val1 / num2;
2.6
Interactive Programs
It is often useful to design a program to read data from the user interactively dur-
ing execution. That way, new results can be computed each time the program is
run, depending on the data that is entered.
The
Scanner
Class
The
Scanner
class, which is part of the standard Java class library,
provides convenient methods for reading input values of various
types. The input could come from various sources, including data
typed interactively by the user or data stored in a file. The
Scanner
class can also be used to parse a character string into separate pieces.
Figure 2.7 lists some of the methods provided by the
Scanner
class.
We must first create a
Scanner
object in order to invoke its methods. Objects
in Java are created using the
new
operator. The following declaration creates a
Scanner
object that reads input from the keyboard:
KEY CONCEPT
The
Scanner
class provides methods
for reading input of various types
from various sources.
Scanner scan =
new
Scanner (System.in);
This declaration creates a variable called scan that represents a
Scanner
object.
The object itself is created by the
new
operator and a call to a special method
Search WWH ::
Custom Search