Java Reference
In-Depth Information
2.4
Identify and correct the errors in each of the following statements:
a)
if (c <
7
);
System.out.println(
"c is less than 7"
);
b)
if (c =>
7
)
System.out.println(
"c is equal to or greater than 7"
);
2.5
Write declarations, statements or comments that accomplish each of the following tasks:
a) State that a program will calculate the product of three integers.
b) Create a
Scanner
called
input
that reads values from the standard input.
c) Declare the variables
x
,
y
,
z
and
result
to be of type
int
.
d) Prompt the user to enter the first integer.
e) Read the first integer from the user and store it in the variable
x
.
f) Prompt the user to enter the second integer.
g) Read the second integer from the user and store it in the variable
y
.
h) Prompt the user to enter the third integer.
i) Read the third integer from the user and store it in the variable
z
.
j) Compute the product of the three integers contained in variables
x
,
y
and
z
, and assign
the result to the variable
result
.
k) Use
System.out.printf
to display the message
"Product
is"
followed by the value of
the variable
result
.
2.6
Using the statements you wrote in Exercise 2.5, write a complete program that calculates
and prints the product of three integers.
Answers to Self-Review Exercises
2.1
a) left brace (
{
), right brace (
}
). b)
if
. c)
//
. d) Space characters, newlines and tabs.
e) Keywords. f)
main
. g)
System.out.print
,
System.out.println
and
System.out.printf
.
2.2
a)
False. Comments do not cause any action to be performed when the program executes.
They're used to document programs and improve their readability.
b)
True.
c)
False. Java is case sensitive, so these variables are distinct.
d)
False. The remainder operator can also be used with noninteger operands in Java.
e)
False. The operators
*
,
/
and
%
are higher precedence than operators
+
and
-
.
2.3
a)
int
c, thisIsAVariable, q76354, number;
or
int
c;
int
thisIsAVariable;
int
q76354;
int
number;
b)
System.out.print(
"Enter an integer: "
);
c)
value = input.nextInt();
d)
System.out.println(
"This is a Java program"
);
e)
System.out.printf(
"%s%n%s%n", "This is a Java", "program"
);
f)
if
(number !=
7
)
System.out.println(
"The variable number is not equal to 7"
);
2.4
a)
Error: Semicolon after the right parenthesis of the condition
(c
<
7
) in the
if
.
Correction: Remove the semicolon after the right parenthesis. [
Note:
As a result, the
output statement will execute regardless of whether the condition in the
if
is true.]
b)
Error: The relational operator
=>
is incorrect. Correction: Change
=>
to
>=
.