Chapter 4 Introduction to Control Statements

advertisement
Chapter 4
Introduction to Control Statements
(Branching Statements)
Go
Section 1 - Additional Java Operators
Go
Section 2 - If Statements
Go
Section 3 - If-Else Statements
Go
Section 4 - Extended If Statements
Chapter 4 Section 1
Additional Java Operators
• Extended Assignment Operators
• Increment & Decrement Operators
• Relational Operators
• Logical Operators
4.1 Extended Assignment Operators
These are special assignment operators for arithmetic
operations and concatenation.
They have the same precedence as the standard assignment
operator =.
Here are the extended assignment operators:
+= Addition and Concatenation
-= Subtraction
*= Multiplication
/= Division
%= Modulus
3
4.1 Extended Assignment Operators
Look closely at the lines of code that use the extended
assignment operators below and see the equivalent lines of
code. Look closely at the values stored in the variables x
and str after the lines are executed.
int x = 10;
String str = “Java”;
x += 5;
// equivalent to x = x + 5;
x now holds 15
x -= 3;
// equivalent to x = x - 3;
x now holds 12
x *= 2;
// equivalent to x = x * 2;
x now holds 24
x /= 4;
// equivalent to x = x / 4;
x now holds 6
x %= 5;
// equivalent to x = x % 5;
x now holds 1
str += “ Rules!”; // equivalent to str = str + “ Rules”; str holds “Java Rules”
4
4.1 The Increment & Decrement Operators
The Increment operator is ++
It increases the value of an int or double variable by 1.
The Decrement operator is -–
It decreases the value of an int or double variable by 1.
The following code shows you how to use ++ and -int x = 10;
int y = 20;
double w= 7.8;
double z = 14.3;
x++;
// equivalent to x = x + 1; or x += 1; x now holds 11
y--;
// equivalent to y = y - 1; or y -= 1;
y now holds 19
w++;
// equivalent to w = w + 1; or w += 1; w now holds 8.8
z--;
// equivalent to z = z - 1; or z -= 1;
z now holds 13.3
–
5
4.1 Relational Operators
Relational operators are used to form Boolean Expressions for if
and while statements. Here are the six relational operators:
Operator
6
Relationship
==
equal to
!=
not equal to
<
less than
<=
less than or equal to
>
greater than
>=
greater than or equal to
You’ll see
how to use
these soon.
Do not place a space between the operators that use
two symbols … >= <= == or !=
4.1 Logical Operators
Logical operators are used to modify or form compound Boolean
Expressions for if and while statements. There are three logical
operators:
Operator
Relationship
!
Not
&&
And
||
Or
Do not place a space between the operators that use
two symbols … && and | |
7
You’ll see
how to use
these soon.
4.1 Precedence Rules for Logical Operators
8
Chapter 4 Section 2
If Statments
4.2 Introduction to If Statements
In Java you can execute a segment of code if a Boolean
condition is true. So if the Boolean condition is false, then
nothing is executed.
Here is the general form of an if statement:
if (some Boolean expression is true)
{
// execute this code only between the curly braces
}
The code inside the if statement is NOT executed if the boolean
condition is false.
Note that curly braces { } encompass all of the statements inside
the body of the if statement. There can be one or many.
10
4.2 Evaluating Boolean Expressions
int a = 3, b = 7, c = 10, d = -20;
if (a < b)
is true
if (a <= b)
is true
if (a == b)
is false
if (a != b)
is true
if (a - b > c + d)
is true
if ( a < b < c)
invalid Java statement but valid in algebra
if (a == b == c)
invalid Java statement
You will be shown how to accomplish the last two statements later.
11
4.2 If Statement Example
Consider the following code:
System.out.print (“Enter an integer: ”);
int num = reader.nextInt();
if (num % 5 == 0)
{
System.out.print (num + “is evenly divisible by 5”);
}
Note the use of the equals operator == to compare the two
values of num % 5 and 0 to see if they are equivalent. If they
are equivalent the entire expression evaluates to true,
otherwise it evalutes to false and nothing is printed.
12
4.2 if Statement Code Example
Here is code that will calculate a salesperson’s pay. It will
double a salesperson’s commission from 10% to 20% if sales
are over $2,000.00:
double commission = 0.10; // regular commission is 10%
System.out.print(“Enter the person’s sales for the month: ”);
double sales = reader.nextDouble();
if (sales > 2000.00)
commission *= 2;
double pay = sales * commission;
System.out.println(“Your pay is: ” + pay);
13
Note: if there is only one
line of code inside the if
statement, then you don’t
have to put curly braces
around the body of the if,
but we indent to show for
readability to sho that it is
inside the if statement. If
we didn’t indent it would still
be inside the if statement.
4.2 if Statement Code Example
If a worker is paid $8.50 per hour for all hours up to and including
40 hours per week, but is paid a time and a half wage of $12.75
per hour for any hours over 40 hours per week, then the person’s
pay could be calculated using the following:
System.out.print(“Enter the number of hours worked this week: ”);
double hoursWorked = reader.nextDouble();
double pay = hoursWorked * 8.50;
if (hoursWorked > 40)
{
double overTimeHours = hoursWorked - 40;
pay += overTimeHours * 4.25;
}
System.out.println(“The employee’s pay is: ” + pay);
14
4.2 The Form of an if Statement
Either use of curly braces below works, but the second is preferred
for readabiltiy and troubleshooting!
if (condition) {
// saves lines by putting { on same line of condition
statement;
statement;
}
No semicolon goes here!
if (condition)
{
statement;
statement;
}
No semicolon goes here!
// adds readability by putting curly brace { here
// because braces are indented at
// the same level (preferred)
// Easier to find curly brace problems!!!
Note: the statements are executed only if the condition is true,
otherwise this control statement is skipped and nothing is executed.
15
4.2 The Form of an if Statement
No curly braces needed when only one statement is in the branch.
if (condition)
statement;
If curly braces aren’t used, then only the first statement following the if
(condition) is in the branch, even if the second statement is accidently
indented. Remember: compilers ignore spacing and indentation.
Programmers use them for readability.
if (condition)
statement1;
statement2;
statement2 is indented but it is not in the if statement since there are
no curly braces. Another example is on the next slide.
16
4.2 if Statement Indentation Error
if (grade > 100)
System.out.println(“You cannot have a grade over 100.”);
System.out println(“Test score is within range.”);
Here the first println statement is executed only when grade is greater
than 100. The second println statement is incorrectly indented and
will be executed even if the first one is not.
Sometimes programmers get in a hurry and don’t write branching
statements correctly.
How might you rewrite the one above?
17
4.2 if Statement Indentation Error
How might you rewrite the one on the previous slide so it is readable and
shows what is intended?
if (grade > 100)
first version
{
System.out.println(“You cannot have a grade over 100.”);
}
System.out println(“Test score is within range.”);
or
second version
if (grade > 100)
System.out.println(“You cannot have a grade over 100.”);
System.out println(“Test score is within range.”);
Note the blank line after the first System.out.println in the second version.
18
Chapter 4 Section 3
If-Else Statments
4.3 Introduction to If-Else Statements
In Java you can execute one segment of code if a boolean condition is true or
you can execute another segment of code if the condition is false by using
an if-else statement. An if-else statement looks like this:
if (some Boolean expression is true)
{
// execute this code only if the Boolean expression is true
}
else
{
// execute this code only if the Boolean expression is false
}
Note the { } that encompass all of the statements inside the if branch and
another set of { } encompass all of the statements inside the else branch.
20
Curly braces always occur in pairs!
4.3 if-else Statement Code Example
System.out.print(“Enter an integer: ”);
int a = reader.nextInt();
System.out.print(“Enter another integer: ”);
int b = reader.nextInt();
int c;
// Set c equal to the larger of a and b
if ( a > b)
c = a;
else
c = b;
21
4.3 if-else Statement Code Example
Here is code that will calculate a salesperson’s pay. It will double a salesperson’s commission
from 10% to 20% if sales are over $2,000.00, but it is written differently from what we saw
before:
double commission;
System.out.print(“Enter the person’s sales for the month: ”);
double sales = reader.nextDouble();
if (sales > 2000.00)
{
commission = 0.20; // bonus commission is 20%
}
else
{
commission = 0.10; // regular commission is 10%
}
double pay = sales * commission;
System.out.println(“Your pay is: ” + pay);
22
4.3 if-else Statement Code Example
If a worker is paid $8.50 per hour for all hours up to and including 40
hours per week, but is paid a time and a half wage of $12.75 per hour
for any hours over 40 hours per week, then the person’s pay could be
calculated using the following:
System.out.print(“Enter the number of hours worked this week: ”);
double hoursWorked = reader.nextDouble();
double pay;
if (hoursWorked <= 40)
pay = hoursWorked * 8.50;
else
{
pay = 40 * 8.5 + (hoursWorked - 40) * 12.75;
}
System.out.println(“The employee’s pay is: ” + pay);
23
4.3 Checking Input with if-else Statements
if-else statements are commonly used to check user inputs before
processing them.
System.out.print("Enter the radius: ");
double radius = reader.nextDouble();
if (radius < 0)
System.out.println("Error: Radius must be >= 0");
else
{
double area = Math.PI * Math.pow(radius, 2);
System.out.println("The area is " + area);
}
24
4.3 Comparison of if-else Statement Formats
Either use of curly braces works:
if (condition) {
statement;
statement;
} else {
statement;
statement;
}
Here you see the two ways
of formatting an if-else
statement. Either works.
less lines
The other one doesn’t so
that the curly braces can
more easily seen as
matched pairs.
One places the curly braces
on the same lines as the if
condition and the else
keyword.
if (condition)
{
statement;
statement;
}
else
{
statement;
statement;
}
greater readability
Note: the statements in the if branch are executed only if the condition is true,
otherwise the statements in the else branch are executed.
One of the two branches will always be executed when you have an if-else statement.
25
4.3 Forms of if and if-else Statements
if and if-else statements can have one or more statements in any
branch as seen in the variety below:
if (condition)
statement;
if (condition)
{
statement;
statement;
}
if (condition)
statement;
else
statement;
26
if (condition)
{
statement;
…..
statement;
}
else
statement;
if (condition)
statement;
else {
statement;
………..
statement;
}
4.3 Important Things about if Statements
•
It is better to over-use braces than to under-use them. This
can help to eliminate logic errors by adding readability.
•
The condition of an if statement must be a Boolean
expression that evaluates to either true or false.
•
A flowchart can be used to illustrate the behavior of if and
if-else statements and develop an over all flow-of-control
for a programming segment.
27
4.3 if and if-else Flow Charts
Flowcharts for the if and if-else statements
28
4.3 Simple Boolean Conditions
You have learned that Java allows you to use an if statement of the
form:
if (condition)
{
….
}
The condition can be a simple boolean expression or a compound
boolean expression.
Here is a simple boolean expression:
if (grade > 90)
System.out.println(“Your grade is A”);
29
4.3 Compound Boolean Conditions
Java allows you to use an if statement that has a compound
boolean expression in the condition. Compound boolean
expressions use the logical operators:
&& (referred to as “AND”)
| | (referred to as “OR”)
! (referred to as “NOT”)
Here are examples using each one:
if (grade > 90 && grade <= 100)
System.out.println(“Your grade is A”);
if (grade < 0 | | grade > 100)
System.out.println(“Grade not possible.”);
if ( ! (grade > 59) )
System.out.println(“Your grade is an F”);
30
Chapter 4 Section 4
Nested If
and
Extended If
Statments
4.4 Extended if Statement Form
Extended if statements have two or more branches.
They have the following general form:
if (condition)
{
Only one of the three branches of
code will be executed.
… code
}
else if (condition)
{
The else if branch has a condition.
… code
}
else
{
… code
32
}
The else branch is optional,
but if none of the conditions
in the other branches are
true then the else branch will
be executed.
4.4 Extended if Statement without Else
An extended if statement need not have an else branch. If it
doesn’t, then code will only be executed if one of the two
conditions is true, otherwise nothing is executed.
if (condition)
{
… code
}
else if (condition)
{
… code
}
33
4.4 Multiple Branches of an Extended if
if (condition)
{
… code
}
else if (condition)
{
… code
}
else if (condition)
{
… code
}
….. other else if branches
else
{
… code
34
}
An extended if statement may
have many branches. No
matter how many branches it
has only one branch of code
will be executed. If it does not
have an ending else branch,
then again it is possible no
code will be executed.
However, if it does have an
ending else branch then if
none of the conditions in the
other branches are true then
the else branch will be
executed.
4.4 Modifying Three if Statements
Consider the pseudocode for the following simple if statements. Even
though they have compound boolean expressions, the intention of
the code is clear when they follow one another in this order. Here
all three if conditions are tested but it is possible that some of them
may not be executed:
if (the time is after 7pm && you have a book)
read the book
if (the time is after 7pm && ! you have a book)
watch TV
if ( ! the time is after 7pm)
go for a walk
We will convert the above code to an extended if statement.
35
4.4 Extended if Statements
Here the if statements have been rewritten as an extended if
statement and the code overall is more readable and it is
more efficient because once Java finds a true condition, then
that branch is executed and all other branches are skipped!
if (the time is after 7pm && you have a book)
read the book
else if (the time is after 7pm && ! you have a book)
watch TV
else if ( ! the time is after 7pm)
go for a walk
Remember ... you don’t have to have a final else to end an extended if
statement, but you can if you want something to be executed if none of
the boolean conditions of the extended if are true.
36
4.4 Extended if Statements
if (the time is after 7pm && you have a book)
read the book
else if (the time is after 7pm && ! you have a book)
watch TV
else if ( ! the time is after 7pm)
go for a walk
In an extended if statement like this one, it is easier to read and
trace the logic and make sure that every possible situation is
covered. Therefore, we are able to avoid logic errors. It is more
difficult in the next nested if statement.
37
4.4 Nested if Statement Logic Errors
The nested if statement below is equivalent to the previous
extended if, but it is not as easy to read and is more difficult
to trace the logic to make sure every possibility is covered. It
takes more time to think about it and verify its correctness.
if (the time is after 7pm)
{
if (you have a book)
read the book
else
watch TV
} else
go for a walk
38
4.4 Flow Chart for a Nested If Statement
This flowchart of a
nested if statement
helps us verify the code
in a visual manner.
Most of the time when
we can visualize code
we can verify its
correctness.
39
4.4 Evolution of an Extended If Statement
The next three slides will show you how extended if
statements are actually nested if statements.
40
if (testAverage >= 90)
System.out.print(“Grade is A. ”);
else {
if (testAverage >= 80)
System.out.print(“Grade is B. ”);
else {
if (testAverage >= 70)
System.out.print(“Grade is C. ”);
else {
if (testAverage >= 60)
System.out.print(“Grade is D. ”);
else {
System.out.print(“Grade is F. ”);
}
}
}
}
4.4 Nested
if Statement
Example with
the { } braces
in the elses.
Note: there is only one
java statement inside
each if statement so there
are no curly braces for
those branches.
There is also just one
statement in each else
statement even though
they have { }, but we will
remove the curly braces.
(See next slide)
if (testAverage >= 90)
System.out.print(“Grade is A. ”);
else
if (testAverage >= 80)
System.out.print(“Grade is B. ”);
else
4.4 Nested
if Statement
Example
without the { }
braces.
if (testAverage >= 70)
System.out.print(“Grade is C. ”);
else
if (testAverage >= 60)
System.out.print(“Grade is D. ”);
else
System.out.print(“Grade is F. ”);
Note: java doesn’t care
about spacing or
indentation so we can
move the if statements up
to the same line as the
else once the curly braces
are removed.
(See next slide)
if (testAverage >= 90)
System.out.print(“Grade is A. ”);
else if (testAverage >= 80)
System.out.print(“Grade is B. ”);
else if (testAverage >= 70)
System.out.print(“Grade is C. ”);
4.4 Nested
if Statement
Example without
the { } braces
and reformatted
to be an
extended if
statement.
else if (testAverage >= 60)
System.out.print(“Grade is D. ”);
else
System.out.print(“Grade is F. ”);
Now we have a nice
readable statement that
makes sense because it
is easy to read.
4.4 Extended if Statement Order
if (testAverage >= 60)
System.out.print(“Grade is D. ”);
else if (testAverage >= 70)
System.out.print(“Grade is C. ”);
else if (testAverage >= 80)
System.out.print(“Grade is B. ”);
If we coded the
previous extended if
with the conditions in
reverse order and
entered 93 for the
testAverage, what
would happen?
else if (testAverage >= 90)
System.out.print(“Grade is A. ”);
else
System.out.print(“Grade is F. ”);
(see next slide)
4.4 Extended if Statement Order
if (testAverage >= 60)
System.out.print(“Grade is D. ”);
else if (testAverage >= 70)
System.out.print(“Grade is C. ”);
else if (testAverage >= 80)
System.out.print(“Grade is B. ”);
If we coded the
previous extended if
with the conditions in
reverse order and
entered 93 for the
testAverage, what
would happen?
else if (testAverage >= 90)
System.out.print(“Grade is A. ”);
else
System.out.print(“Grade is F. ”);
The program would
display a “D”.
4.4 Extended if Statements
with compound boolean expressions
However if we change the simple boolean expression listed first
to a compound boolean expression then we ensure the code’s
accuracy.
if (testAverage >= 60)
System.out.print(“Grade is D. ”);
becomes
if (testAverage >= 60 && testAverage < 70)
System.out.print(“Grade is D. ”);
(see next slide for the expanded example)
4.4 Extended if Statements
with compound boolean expressions
Here is a full extended if with compound boolean expressions, where
the order of the branches doesn’t matter.
if (testAverage >= 90 && testAverage <= 100)
System.out.print(“Grade is A. ”);
else if (testAverage >= 80 && testAverage < 90)
System.out.print(“Grade is B. ”);
else if (testAverage >= 70 && testAverage < 80)
System.out.print(“Grade is C. ”);
else if (testAverage >= 60 && testAverage < 70)
System.out.print(“Grade is D. ”);
else
System.out.print(“Grade is F. ”);
Chapter 4 Review
•
The Math class provides several useful methods, such as
pow , sqrt,random and abs.
•
Java’s extended assignment operators are +=, -=, *=, /=, %=
•
Java’s has increment ++ and decrement -- operators that
modify a double or int variable by 1.
•
Java has the logical operators &&, ||, and ! that can be used
in forming boolean expressions.
•
Java has the relational operators <, <=, >, >=, ==, and !=
They compare two values and return a Boolean value. They
are used to form Boolean expressions in the conditions of
control statements.
48
Chapter 4 Review
•
Use an if-else statement rather than two if statements
when the alternative courses of action are mutually exclusive.
This makes your code more efficient when the segment needs
to executed many times.
•
The presence or absence of the {} symbols can seriously
affect the logic of a control statement.
•
When testing programs that use if or if-else statements,
use test data that forces the program to exercise all logical
branches.
49
Chapter 4 Summary
•
if and if-else statements are used to make one-way and
two-way decisions.
•
Extended if statements have multiple branches that allow for
a straight forward way for processing data when compound
boolean expressions are used in the branches. The use of
compound boolean expressions when possible eliminates
the need for a precise ordering of the branches.
•
An extended if statement can have an ending else branch
that will be executed only if all other branch conditions are
false. If there is no ending else branch, then it is possible
that none of the code in the branches will be executed.
50
Download