



























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




























Control Statements
Selection Statements
Using if and if...else
Nested if Statements
Using switch Statements
Conditional Operator
Looping: while, do-while, and for
Nested loops
Using break and continue
Adding a semicolon at the end of an if
clause is a common mistake.
if (radius >= 0);
{
area = radiusradiusPI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
This mistake is hard to find, because it is
not a compilation error or a runtime error,
it is a logic error.
This error often occurs when you use the
next-line block style.
Wrong
if (radius >= 0) {
area = radiusradiusPI;
System.out.println("The area for the “
" is " + area);
}
else {
System.out.println("Negative input");
}
if (score >= 90)
grade = ‘A’;
else
if (score >= 80)
grade = ‘B’;
else
if (score >= 70)
grade = ‘C’;
else
if (score >= 60)
grade = ‘D’;
else
grade = ‘F’;
if (score >= 90)
grade = ‘A’;
else if (score >= 80)
grade = ‘B’;
else if (score >= 70)
grade = ‘C’;
else if (score >= 60)
grade = ‘D’;
else
grade = ‘F’;
Nothing is printed from the preceding statement. To force
the else clause to match the first if clause, you must add a
pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.
numOfYears
7
15 30
default
Next
Statement
annualInterestRate=7.25 annualInterestRate=8.50 annualInterestRate=9.0 System.out.println("Wrong number of " +
"years, enter 7, 15, or 30");
System.exit(0);
The switch-expression must yield a value of char, byte, short,
or int type and must always be enclosed in parentheses.
The value1, ..., and valueN must have the same data type as
the value of the switch-expression. The resulting statements
in the case statement are executed when the value in the case
statement matches the value of the switch-expression. (The
case statements are executed in sequential order.)
The keyword break is optional, but it should be used at the
end of each case in order to terminate the remainder of the
switch statement. If the break statement is not present, the
next case statement will be executed.
Do not forget to use a break statement when one is needed.
For example, the following code always displays Wrong
number of years regardless of what numOfYears is. Suppose
the numOfYears is 15. The statement annualInterestRate =
8.50 is executed, then the statement annualInterestRate = 9.0,
and finally the statement System.out.println("Wrong number
of years").
switch (numOfYears) {
case 7: annualInterestRate = 7.25;
case 15: annualInterestRate = 8.50;
case 30: annualInterestRate = 9.0;
default: System.out.println("Wrong number of years");
}