Java Reference
In-Depth Information
program runs, you are prompted to enter values for
feet
and
inches
. Therefore, a read
statement is much more versatile than an assignment statement.
Sometimes it is necessary to initialize a variable by using an assignment statement. This is
especially true if the variable is only used for internal calculation and not for reading and
storing data.
2
Recall that Java might not automatically initialize all the variables when they are
declared. Some variables can be initialized when they are declared, whereas others
must be initialized using either an assignment statement or a read statement.
(Variable initialization is covered in more detail in Chapter 8.)
Suppose you want to store a character into a
char
variable using an input statement. During
program execution, when you input the character, you do not include the single quotation
marks. Suppose that
ch
is a
char
variable. Consider the following input statement:
ch = console.next().charAt(0);
If you want to store
K
in
ch
using this statement, during program execution you type
K
without the single quotation marks. Similarly, if you want to store a string in a
String
variable using an input statement, during program execution you enter only the string
without the double quotation marks.
Suppose the next input is a single printable character, say,
A
. Further suppose that
ch
is a
char
variable. To input
A
into
ch
, you can use the following statement:
ch = console.next().charAt(0);
where
console
is as declared previously.
When something goes wrong in a program and the results it generates are not what you expect,
you should do a walk-through of the statements that assign values to your variables. Example 2-
18 illustrates how to do this. The walk-through is an effective debugging technique.
EXAMPLE 2-18
This example further illustrates how assignment statements and input statements manip-
ulate variables. Consider the following declarations:
static
Scanner console =
new
Scanner(System.in);
int
firstNum;
int
secondNum;
char
ch;
double
z;
Search WWH ::
Custom Search