0% found this document useful (0 votes)
62 views139 pages

CPCS202 03 Selections S19

Uploaded by

Al Su
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views139 pages

CPCS202 03 Selections S19

Uploaded by

Al Su
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 139

Chapter 3:

Selections
Objectives
▪ To declare boolean variables and write Boolean expressions using relational
operators (§3.2).
▪ To implement selection control using one-way if statements (§3.3).
▪ To implement selection control using two-way if-else statements (§3.4).
▪ To implement selection control using nested if and multi-way if statements
(§3.5).
▪ To avoid common errors and pitfalls in if statements (§3.6).
▪ To generate random numbers using the Math.random() method (§3.7).
▪ To program using selection statements for a variety of examples
(SubtractionQuiz, BMI, ComputeTax) (§§3.7–3.9).
▪ To combine conditions using logical operators (&&, ||, and !) (§3.10).
▪ To program using selection statements with combined conditions (LeapYear,
Lottery) (§§3.11–3.12).
▪ To implement selection control using switch statements (§3.13).
▪ To write expressions using the conditional expression (§3.14).
▪ To examine the rules governing operator precedence and associativity (§3.15).
▪ To apply common techniques to debug errors (§3.16).
Motivations
Consider this problem from Chapter 2:

© Dr. Jonathan Cazalas Chapter 3: Selections page 3


Motivations
What happens if the user inputs a negative value
for radius?
– the program would print an invalid result.
If the radius is negative, you don't want the
program to compute the area.
How can you deal with this situation?

© Dr. Jonathan Cazalas Chapter 3: Selections page 4


Motivations
Java provides selection statements, which allow
you to choose actions based on certain conditions
For example, the following selection statement
could be used in the previous program:

© Dr. Jonathan Cazalas Chapter 3: Selections page 5


Motivations
Selection statements use conditions to test if
something is true or false
– These conditions are known as Boolean expressions
A Boolean expression is an expression that
evaluates to a Boolean value (true or false).
We now introduce Boolean types and relational
operators

© Dr. Jonathan Cazalas Chapter 3: Selections page 6


The boolean Type and Operators
Often in a program you need to compare two
values, such as whether i is greater than j.
– Or if an inputted value, such as radius, is less
than zero.
Java provides six relational operators (also
known as comparison operators) that can be
used to compare two values.

© Dr. Jonathan Cazalas Chapter 3: Selections page 7


Relational Operators

© Dr. Jonathan Cazalas Chapter 3: Selections page 8


The boolean Type and Operators
The result of comparing two values is a
Boolean value: true or false.
For example, the following prints true:
System.out.println(2 > 1);
And the following prints false:
System.out.println(3 > 7);

© Dr. Jonathan Cazalas Chapter 3: Selections page 9


The boolean Type and Operators
A variable that holds a Boolean value is known
as a Boolean variable
– The boolean data type is used to declare Boolean
variables
– A Boolean variable can hold one of two values
true or false
– For example, the following statement assigns the
value true to the variable lightsOn:
boolean lightsOn = true;

© Dr. Jonathan Cazalas Chapter 3: Selections page 10


Assuming that x is 1, show the result of the
following Boolean expressions:
a. (x > 0) true
b. (x < 0) false
c. (x != 0) true
d. (x >= 0) true
e. (x != 1) false
f. (x == 1) true

© Dr. Jonathan Cazalas Chapter 3: Selections page 11


if Statements
The previous program would display a message
such as “6 + 2 = 7 is false”
What if you wanted to print something else, such
as “6 + 2 = 7 is incorrect”
How would you do this?
– Answer: selection statements!
Java has several types of selection statements:
– one-way if statements, two-way if-else statements,
nested if statements, multi-way if-else statements,
switch statements, and conditional expressions
© Dr. Jonathan Cazalas Chapter 3: Selections page 12
One-way if Statements
A one-way if statement executes an action if and
only if the condition is true
– Syntax:
if (boolean-expression) {
statement(s);
}

– The flowchart to the right


demonstrates the syntax of
an if statement.

© Dr. Jonathan Cazalas Chapter 3: Selections page 13


One-way if Statements
So if the boolean-expression evaluates to
true, the statements in the block are executed

Example:
if (radius >= 0) {
area = radius * radius * PI;
System.out.println(“The area ” +
“for the circle ” +
“of radius ” + radius +
“ is ” + area);
}

© Dr. Jonathan Cazalas Chapter 3: Selections page 14


Note
The boolean-expression should be enclosed in
parenthesis:
if i > 0 { if (i > 0) {
System.out.println("i is positive"); System.out.println("i is positive");
} }
(a) Wrong (b) Correct

The block braces can be removed if they enclose a single


statement
if (i > 0) { if (i > 0)
System.out.println("i is positive"); Equivalent System.out.println("i is positive");
}

(a) (b)

– but if several statements are inside the if, then the block braces are required

© Dr. Jonathan Cazalas Chapter 3: Selections page 15


Program 1: SimpleIfDemo
Write a program that prompts the user to enter an
integer. If the number is a multiple of 5, the
program should print HiFive. If the number is
divisible by 2, the program should print HiEven.
Remember:
– Step 1: Problem-solving Phase
– Step 2: Implementation Phase

© Dr. Jonathan Cazalas Chapter 3: Selections page 16


Program 1: SimpleIfDemo
Step 1: Problem-solving Phase
– Algorithm:
1. Prompt the user to enter an integer
2. Scan the value from user and save to variable number
3. If number is a multiple of 5, print HiFive.
if (number % 5 == 0)
4. If number is divisible by 2, print HiEven.
if (number % 2 == 0)

© Dr. Jonathan Cazalas Chapter 3: Selections page 17


Program 1: SimpleIfDemo
Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 3: Selections page 18


Program 1: SimpleIfDemo
Run the Program:

Click here to view and trace code

© Dr. Jonathan Cazalas Chapter 3: Selections page 19


Write an if statement that increases pay by 3%
if score is greater than 90.
if (score > 90) {
pay = pay + pay*0.03;
}
or
if (score > 90) {
pay *= 1.03; // same as
} // pay = pay * 1.03;

© Dr. Jonathan Cazalas Chapter 3: Selections page 20


Two-way if-else Statements
A one-way if statement performs an action if the
given condition is true.
– If the condition is false, nothing is done.
But what if you want to take alternative actions
when the condition is false?
Answer: use a two-way if-else statement.
The actions specified by a two-way if-else
statement differ based on whether the condition is
true or false
© Dr. Jonathan Cazalas Chapter 3: Selections page 21
Two-way if-else Statements
Syntax:
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}

© Dr. Jonathan Cazalas Chapter 3: Selections page 22


Two-way if-else Statements
If the boolean-expression evaluates to true, the
statement(s) for the true case are executed
Else, the statement(s) for the false case are
executed
Example:

© Dr. Jonathan Cazalas Chapter 3: Selections page 23


Two-way if-else Statements
Another example:
– Check whether a number is even or odd

© Dr. Jonathan Cazalas Chapter 3: Selections page 24


Check Point
Write an if statement that increases pay by 3%
if score is greater than 90, otherwise increases
pay by only 1%.

Solution:
if (score > 90)
pay *= 1.03;
else
pay *= 1.01;

© Dr. Jonathan Cazalas Chapter 3: Selections page 25


Nested if and
Multi-Way if-else Statements
The statement inside an if or if-else
statement can be any legal Java statement
– including another if or if-else statement!
The inner if statement is said to be nested inside
the outer if statement This statement is nested inside
the if (i > k) statement
Example:

© Dr. Jonathan Cazalas Chapter 3: Selections page 26


Nested if and
Multi-Way if-else Statements
More details:
– The inner if statement can contain another if statement
– In fact, there is no limit to the depth of the nesting

So what is the purpose?


– The nested if statement can be used to implement
multiple alternatives
– Consider the following example, which prints a letter
grade according to the final number grade

© Dr. Jonathan Cazalas Chapter 3: Selections page 27


Nested if and
Multi-Way if-else Statements

– While (a) works, the preferred format for multiple alternatives


is shown in (b) using a multi-way if-else statement
– This multi-way if-else style avoids deep indentation and
makes the program easier to read
© Dr. Jonathan Cazalas Chapter 3: Selections page 28
Nested if and
Multi-Way if-else Statements

© Dr. Jonathan Cazalas Chapter 3: Selections page 29


animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

© Dr. Jonathan Cazalas Chapter 3: Selections page 30


animation
Trace if-else statement
Suppose score is 70.0 The condition is false

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

© Dr. Jonathan Cazalas Chapter 3: Selections page 31


animation
Trace if-else statement
Suppose score is 70.0 The condition is true

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

© Dr. Jonathan Cazalas Chapter 3: Selections page 32


animation
Trace if-else statement
Suppose score is 70.0 grade is C

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

© Dr. Jonathan Cazalas Chapter 3: Selections page 33


animation
Trace if-else statement
Suppose score is 70.0 Exit the if statement

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B"); Note:
else if (score >= 70.0) A condition is only tested
when all the conditions that
System.out.print("C"); come before it are false.
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");

© Dr. Jonathan Cazalas Chapter 3: Selections page 34


Given the following code, show the output when:
x = 2 and y = 3
x = 3 and y = 2
x = 3 and y = 3

© Dr. Jonathan Cazalas Chapter 3: Selections page 35


Common Errors and Pitfalls
Common Error 1: Forgetting Necessary Braces
– Remember: braces can be removed IF the block only
contains a single statement (only one statement)
– However, if there are multiple statements, brackets are
required.
– A common error is to forget these required braces
when grouping multiple lines together

© Dr. Jonathan Cazalas Chapter 3: Selections page 36


Common Errors and Pitfalls
Common Error 1: Forgetting Necessary Braces

– (a) is wrong
the braces are required
– (b) is correct
the required braces are now included

© Dr. Jonathan Cazalas Chapter 3: Selections page 37


Common Errors and Pitfalls
Common Error 2: Wrong Semicolon at the if Line
– There should *not* be a semicolon at the end of the
if line.
– This is a common mistake new programmers make.
And this mistake is hard to find, because it is a logic error.

© Dr. Jonathan Cazalas Chapter 3: Selections page 38


Common Errors and Pitfalls
Common Error 3: Dangling else Ambiguity
– The code in (a) below has two if clauses and one else
clause. Which if clause is matched by the else clause?
The indentation suggests that the else clause matches the
first if clause.
However, this is NOT correct.

© Dr. Jonathan Cazalas Chapter 3: Selections page 39


Common Errors and Pitfalls
Common Error 3: Dangling else Ambiguity
– The code in (a) below has two if clauses and one else
clause. Which if clause is matched by the else clause?
The else clauses actually matches the second if clause.
The else clause always matches the most recent unmatched
if clause in the same block. See corrected code in (b).

© Dr. Jonathan Cazalas Chapter 3: Selections page 40


Common Errors and Pitfalls
Common Error 3: Dangling else Ambiguity
– If you actually wanted the else clause to match with
the first if clause, then you must add a pair of braces:
int i = 1, j = 2, k = 3;

if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");

– This statement displays B.

© Dr. Jonathan Cazalas Chapter 3: Selections page 41


Common Errors and Pitfalls
Common Pitfall 1: Simplifying Boolean Variable
Assignment
– Often, new programmers write code like (a).

– This is not an error


– But it is better written (and shorter) as shown in (b).

© Dr. Jonathan Cazalas Chapter 3: Selections page 42


Common Errors and Pitfalls
Common Pitfall 2: Avoid Duplicating Code in
Different Cases
– Often, new programmers write duplicate code that
should be combined in one place.

– This is not an error, but it is duplicating efforts.


© Dr. Jonathan Cazalas Chapter 3: Selections page 43
Common Errors and Pitfalls
Common Pitfall 2: Avoid Duplicating Code in
Different Cases
– It is better written as follows:

© Dr. Jonathan Cazalas Chapter 3: Selections page 44


Rewrite the following statement using a Boolean
expression:
if (count % 10 == 0)
newline = true;
else
newline = false;

Solution:
newline = count % 10 == 0;

© Dr. Jonathan Cazalas Chapter 3: Selections page 45


What is the output of the following code if
number is 14, 15, or 30?

© Dr. Jonathan Cazalas Chapter 3: Selections page 46


Program 2: Math Learning Tool+
Write a program that helps a first-grader practice
subtraction.
– The program should randomly generate two single-
digit integers and should then ask the user for the
answer. The program will then display a message
stating if the answer is correct. If wrong, the program
should display the correct answer.
Remember:
– Step 1: Problem-solving Phase
– Step 2: Implementation Phase
© Dr. Jonathan Cazalas Chapter 3: Selections page 47
Program 2: Math Learning Tool+
Step 1: Problem-solving Phase
– How can we generate random numbers?
We used currentTimeMillis() previously
A better approach is to the use the random() method,
which Java provides for you in the Math class.
If you call this method, it will return a random double
value, d, such that 0.0 ≤ d < 1.0
– Examples: 0.832 or 0.258, or 0.927, or 0.004
So from these numbers, how do we get a single digit int
– A number between 0 and 9
Easy: we multiply it by 10 and then cast it as an int
int number1 = (int)(Math.random()*10);
© Dr. Jonathan Cazalas Chapter 3: Selections page 48
Program 2: Math Learning Tool+
Step 1: Problem-solving Phase
– So here is our algorithm:
1. Generate two random numbers
int number1 = (int)(Math.random()*10);
int number2 = (int)(Math.random()*10);
2. Make sure that number1 is larger than number 2. If not,
swap them!
3. Ask the user to answer a question
– Example: “What is 6 - 2?”
4. Scan the user’s answer
5. Print whether the answer is correct.

© Dr. Jonathan Cazalas Chapter 3: Selections page 49


Program 2: Math Learning Tool+
Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 3: Selections page 50


Program 2: Math Learning Tool+
Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 3: Selections page 51


Program 2: Math Learning Tool+
Run the Program:

Click here to view and trace code

© Dr. Jonathan Cazalas Chapter 3: Selections page 52


How do you generate a random integer i, such
that 0 ≤ i < 10 ? int number = (int)(Math.random()*10);
How do you generate a random integer i, such
that 0 ≤ i < 20 ? int number = (int)(Math.random()*20);
How do you generate a random integer i, such
that 10 ≤ i < 20 ? int number = 10 + (int)(Math.random()*10);
How do you generate a random integer i, such
that 10 ≤ i < 50 ? int number = 10 + (int)(Math.random()*40);
Write an expression that returns 0 or 1 randomly.
int number = (int)(Math.random()*2);
© Dr. Jonathan Cazalas Chapter 3: Selections page 53
Program 3: Computing BMI
Write a program that computes the Body Mass
Index (BMI) for the user. Your program should
prompt the user to enter a weight in pounds and
height in inches. Your program should then
compute the BMI and display for the user.
Remember:
– Step 1: Problem-solving Phase
– Step 2: Implementation Phase

© Dr. Jonathan Cazalas Chapter 3: Selections page 54


Program 3: Computing BMI
Step 1: Problem-solving Phase
– Notes:
BMI is a measure of health based on the height and weight
BMI is calculated by taking the weight (in kilograms) and
then dividing it by the square of the height (in meters)
𝑤𝑒𝑖𝑔ℎ𝑡𝐼𝑛𝐾𝑖𝑙𝑜𝑔𝑟𝑎𝑚𝑠
𝐵𝑀𝐼 =
ℎ𝑒𝑖𝑔ℎ𝑡𝐼𝑛𝑀𝑒𝑡𝑒𝑟𝑠 ∗ℎ𝑒𝑖𝑔ℎ𝑡𝐼𝑛𝑀𝑒𝑡𝑒𝑟𝑠

The interpretation of BMI for people 20 years or older is


as follows:

© Dr. Jonathan Cazalas Chapter 3: Selections page 55


Program 3: Computing BMI
Step 1: Problem-solving Phase
– Notes:
So the user input is in pounds and inches
The BMI equation is in kilograms and meters
Therefore, you will need to convert from:
– pounds to kilograms
• One pound is 0.45359237 kilograms
– inches to meters
• one inch is 0.0254 meters

© Dr. Jonathan Cazalas Chapter 3: Selections page 56


Program 3: Computing BMI
Step 1: Problem-solving Phase
– Algorithm:
1. Prompt user for input
2. Scan height and weight from user
3. Compute BMI using BMI equation
4. Display results to user

© Dr. Jonathan Cazalas Chapter 3: Selections page 57


Program 3: Computing BMI
Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 3: Selections page 58


Program 3: Computing BMI
Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 3: Selections page 59


Program 3: Computing BMI
Run the Program:

– Note the use of constants in the program


Makes the conversion formulas easier to read and
understand

Click here to view and trace code

© Dr. Jonathan Cazalas Chapter 3: Selections page 60


Logical Operators
We have used conditional statements to help us
determine if the execution should take one path
(true path) or another path (false path)
– But until now, these conditional statements have been
very basic
Usually, whether a statement is executed is
determined by a combination of several
conditions.
– You can use logical operators to combine these
conditions to form a compound Boolean expression.
© Dr. Jonathan Cazalas Chapter 3: Selections page 61
Logical Operators
Logical operators, also known as Boolean
operators, operate on Boolean values to create a
new Boolean value
The following page shows the four logical
operators we will use
The four pages after that show a truth table for
each logical operator and some examples

© Dr. Jonathan Cazalas Chapter 3: Selections page 62


Logical Operators

Operator Name Description

! not logical negation

&& and logical conjunction

|| or logical disjunction

^ exclusive or logical exclusion

© Dr. Jonathan Cazalas Chapter 3: Selections page 63


Truth Table for Operator !

p !p

true false

false true

© Dr. Jonathan Cazalas Chapter 3: Selections page 64


Truth Table for Operator &&
p1 p2 p1 && p2

false false false

false true false

true false false

true true true

© Dr. Jonathan Cazalas Chapter 3: Selections page 65


Truth Table for Operator ||
p1 p2 p1 || p2

false false false

false true true

true false true

true true true

© Dr. Jonathan Cazalas Chapter 3: Selections page 66


Truth Table for Operator ^
p1 p2 p1 ^ p2

false false false

false true true

true false true

true true false

© Dr. Jonathan Cazalas Chapter 3: Selections page 67


Program 4: TestBooleanOperators
Write a program that tests the usage of boolean
operators. Specifically, your program should
prompt the user to enter one integer. Your
program should then determine if the value is
divisible by 2 and 3, by 2 or 3, or by 2 or 3 but
not both.
Remember:
– Step 1: Problem-solving Phase
– Step 2: Implementation Phase

© Dr. Jonathan Cazalas Chapter 3: Selections page 68


Program 4: TestBooleanOperators
Step 1: Problem-solving Phase
– Notes:
What does it mean “the value is divisible by”?
If a number is divisible by some other number, this means
that it divides perfectly into that number with no remainder
Example:
– 15 is divisible by 3 and also by 5.
– However, 15 is not divisible by 4.
Example:
– 4 is divisible by 2.
– 4 is not divisible by 3.

© Dr. Jonathan Cazalas Chapter 3: Selections page 69


Program 4: TestBooleanOperators
Step 1: Problem-solving Phase
– Notes:
So how do we check for divisibility?
We use mod (%)
Example: check if some number, x, is divisible by 3
if (x % 3 == 0)
This says: if we divide by 3 and the remainder is zero…
And that is exactly what we want!
However, we must check the divisibility of two numbers
– both 2 and 3
This means we must use logical operators
© Dr. Jonathan Cazalas Chapter 3: Selections page 70
Program 4: TestBooleanOperators
Step 1: Problem-solving Phase
– Algorithm:
1. Prompt user for input
2. Scan the integer value from user
3. Determine the divisibility conditions
4. Display results to user

© Dr. Jonathan Cazalas Chapter 3: Selections page 71


Program 4: TestBooleanOperators
Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 3: Selections page 72


Program 4: TestBooleanOperators
Run the Program:

Click here to view and trace code

© Dr. Jonathan Cazalas Chapter 3: Selections page 73


Logical Operators
Final notes:
– If one of the operands of an && operator is false,
then the expression is false.
– If one of the operands of an || operator is true,
then the expression is true.
Java uses these properties to improve the performance of
these operators
– Example:
When evaluating p1 && p2, Java first evaluates p1
If p1 is true, Java will evaluate p2
But if p1 is false, Java will not even check p2
© Dr. Jonathan Cazalas Chapter 3: Selections page 74
Logical Operators
Caution:
– In mathematics, the following expression is correct:
1 <= daysInMonth <= 31

– However, it is not correct in Java, because


1 <= daysInMonth is evaluated to a boolean
value, which cannot be compared to 31
– The correct expression in Java is
(1 <= daysInMonth) && (daysInMonth <= 31)

© Dr. Jonathan Cazalas Chapter 3: Selections page 75


Assuming that x is 1, show the result of the
following Boolean expressions:
a. (true) && (3 > 4) false
b. !(x > 0) && (x > 0) false
c. (x > 0) || (x < 0) true
d. (x != 0) || (x == 0) true
e. (x >= 0) || (x < 0) true
f. (x != 1) == !(x == 1) true

© Dr. Jonathan Cazalas Chapter 3: Selections page 76


Write a Boolean expression that evaluates to true if a
number stored in variable num is between 1 and 100.
– Solution:
(1 <= num) && (num <= 100)

Write a Boolean expression that evaluates to true if a


number stored in variable num is between 1 and 100 or
the number is negative.
– Solution:
(1 <= num) && (num <= 100) || (num < 0)

© Dr. Jonathan Cazalas Chapter 3: Selections page 77


Program 5: Leap Year
Write a program that determines if a given year
is a leap year. Specifically, ask the user to enter a
year. Then determine if that year is a leap year
and display the results.
Remember:
– Step 1: Problem-solving Phase
– Step 2: Implementation Phase

© Dr. Jonathan Cazalas Chapter 3: Selections page 78


Program 5: Leap Year
Step 1: Problem-solving Phase
– Notes:
What is a leap year?
– A leap year has 366 days (instead of 365)
– Why?
– The earth takes approximately 365.25 days to circle around the sun
– However, the Gregorian year has only 365 days
– Therefore, every four years, the number of days is increased to 366
A year is a leap year if it is divisibly by 4 but not by 100, or
if it is divisible by 400.

© Dr. Jonathan Cazalas Chapter 3: Selections page 79


Program 5: Leap Year
Step 1: Problem-solving Phase
– Notes:
Which years are leap years?
There are three criteria:
1. The year must be evenly divisibly by 4
2. If the year can be evenly divided by 100, then it is NOT a leap
year, unless…
3. The year is also evenly divisible by 400. Then it is a leap year.

Summary: a year is a leap year if it is divisibly by 4 but not


by 100, or if it is divisible by 400.

© Dr. Jonathan Cazalas Chapter 3: Selections page 80


Program 5: Leap Year
Step 1: Problem-solving Phase
– Notes:
Summary: a year is a leap year if it is divisibly by 4 but not
by 100, or if it is divisible by 400.
We need to write a Boolean expression to determine if a
given variable, year, is a leap year.
Consider how to convert the above condition into a Boolean
expression.
Solution:
boolean isLeapYear =
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

© Dr. Jonathan Cazalas Chapter 3: Selections page 81


Program 5: Leap Year
Step 1: Problem-solving Phase
– Algorithm:
1. Prompt user for input
2. Scan the year from user
3. Determine if it is a leap year
4. Display results to user

© Dr. Jonathan Cazalas Chapter 3: Selections page 82


Program 5: Leap Year
Step 2: Implementation

© Dr. Jonathan Cazalas Chapter 3: Selections page 83


Program 5: Leap Year
Run the Program:

Click here to view and trace code

© Dr. Jonathan Cazalas Chapter 3: Selections page 84


switch Statements
Nested if statements are very helpful
– The allow us to fully translate our logical conditions
into code
However, overuse of nested if statements can
make a program difficult to read.
Solution: Java provides a switch statement to
simply coding for multiple conditions

© Dr. Jonathan Cazalas Chapter 3: Selections page 85


switch Statements
Here is an example switch statement:
switch (status) {
case 0: code HERE for case 0;
break;
case 1: code HERE for case 1;
break;
case 2: code HERE for case 2;
break;
case 3: code HERE for case 3;
break;
default: System.out.println(“Error: invalid status");
System.exit(1);
}

– Here, status is an int representing a user choice


© Dr. Jonathan Cazalas Chapter 3: Selections page 86
switch Statements
So this switch statement checks to see whether
status matches the value 0, 1, 3, or 3, and in that
exact order.
If the status matches a value, the code for that
status/case is executed.
Then, just like an if statement, the rest of the
code is skipped.
– This is done with the break.
– This will break us out of the switch block.

© Dr. Jonathan Cazalas Chapter 3: Selections page 87


switch Statements
Here is the flowchart for the previous code:

© Dr. Jonathan Cazalas Chapter 3: Selections page 88


switch Statements
Syntax for the switch statement:
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}

© Dr. Jonathan Cazalas Chapter 3: Selections page 89


switch Statements
switch statements obey the following rules:
• switch expression must yield a switch (switch-expression) {
case value1: statement(s)1;
value of char, byte, short, break;
int, or String case value2: statement(s)2;
break;
• char and String types will be ...
introduced in the next chapter case valueN: statement(s)N;
• switch expression must always break;
default: statement(s)-for-default;
be in parenthesis }

© Dr. Jonathan Cazalas Chapter 3: Selections page 90


switch Statements
switch statements obey the following rules:
• The value1, value2, ..., and switch (switch-expression) {
case value1: statement(s)1;
valueN must have the same data break;
type as the value of the switch- case value2: statement(s)2;
break;
expression. ...
• Note that value1, value2, ..., case valueN: statement(s)N;
break;
and valueN are constant default: statement(s)-for-default;
expressions, meaning that they }
cannot contain variables in the
expression, such as 1 + x.

© Dr. Jonathan Cazalas Chapter 3: Selections page 91


switch Statements
switch statements obey the following rules:
• When the value in a case switch (switch-expression) {
case value1: statement(s)1;
statement matches the value of the break;
switch expression, the case value2: statement(s)2;
break;
statements starting from this case ...
are executed. case valueN: statement(s)N;
break;
• Execution will continue until default: statement(s)-for-default;
either a break statement or the }
end of the switch statement is
reached.

© Dr. Jonathan Cazalas Chapter 3: Selections page 92


switch Statements
switch statements obey the following rules:
• The keyword break is optional, switch (switch-expression) {
case value1: statement(s)1;
but it should be used at the end of break;
each case in order to terminate the case value2: statement(s)2;
break;
remainder of the switch statement. ...
• If the break statement is not case valueN: statement(s)N;
break;
present, the next case statement default: statement(s)-for-default;
will be executed. }

• The default case, which is


optional, can be used to perform
actions when none of the specified
cases matches the switch-
expression.

© Dr. Jonathan Cazalas Chapter 3: Selections page 93


switch Statements
With an if/else-if block, once a condition is
met, the code for the condition is executed, and
the rest of the if/else-if block is skipped.
In this same way, with a switch statement, once
a case is correctly found, the code for that case
should be executed, and then the rest of the
switch block should be skipped
– How do we do this?
– We use a break statement

© Dr. Jonathan Cazalas Chapter 3: Selections page 94


switch Statements
break statement:
– Usually you will want to use a break statement at
the end of each case.
This will skip all other cases in the switch statement
– If you do not use a break statement, the next case
will be executed.
– Sometimes, depending on your logic, you may not
want to use a break at the end of each case

© Dr. Jonathan Cazalas Chapter 3: Selections page 95


animation

Trace switch statement

int a= 1;

switch (a) {
case 1: System.out.println(“ONE”);
case 7: System.out.println(“SEVEN”);
case 2: System.out.println(“THREE”);
}

© Dr. Jonathan Cazalas Chapter 3: Selections page 96


animation

Trace switch statement

a is 1:

int a= 1;

switch (a) {
case 1: System.out.println(“ONE”);
case 7: System.out.println(“SEVEN”);
case 2: System.out.println(“THREE”);
}

© Dr. Jonathan Cazalas Chapter 3: Selections page 97


animation

Trace switch statement


Execute this line

int a= 1;

switch (a) {
case 1: System.out.println(“ONE”);
case 7: System.out.println(“SEVEN”);
case 2: System.out.println(“THREE”);
}

Output :
ONE

© Dr. Jonathan Cazalas Chapter 3: Selections page 98


animation

Trace switch statement


Execute this line

int a= 1;

switch (a) {
case 1: System.out.println(“ONE”);
case 7: System.out.println(“SEVEN”);
case 2: System.out.println(“THREE”);
}

Output :
ONE
SEVEN
© Dr. Jonathan Cazalas Chapter 3: Selections page 99
animation

Trace switch statement


Execute this line

int a= 1;

switch (a) {
case 1: System.out.println(“ONE”);
case 7: System.out.println(“SEVEN”);
case 2: System.out.println(“THREE”);
}

Output :
ONE
SEVEN
THREE
© Dr. Jonathan Cazalas Chapter 3: Selections page 100
animation

Trace switch statement


Execute next statement

int a= 1;

switch (a) {
case 1: System.out.println(“ONE”);
case 7: System.out.println(“SEVEN”);
case 2: System.out.println(“THREE”);
}

Next statement;

© Dr. Jonathan Cazalas Chapter 3: Selections page 101


animation

Trace switch statement (break)


Suppose a is 1: Pay attention:
We now use “break” to
exit the switch statement.

int a= 1;

switch (a) {
case 1: System.out.println(“ONE”);
break;
case 7: System.out.println(“SEVEN”);
break;
case 2: System.out.println(“THREE”);
break;
}

© Dr. Jonathan Cazalas Chapter 3: Selections page 102


animation

Trace switch statement (break)


a is 1:

int a= 1;

switch (a) {
case 1: System.out.println(“ONE”);
break;
case 7: System.out.println(“SEVEN”);
break;
case 2: System.out.println(“THREE”);
break;
}

© Dr. Jonathan Cazalas Chapter 3: Selections page 103


animation

Trace switch statement (break)


Execute this line

int a= 1;

switch (a) {
case 1: System.out.println(“ONE”);
break;
case 7: System.out.println(“SEVEN”);
break;
case 2: System.out.println(“THREE”);
break;
}
Output :
ONE
© Dr. Jonathan Cazalas Chapter 3: Selections page 104
animation

Trace switch statement (break)


Execute this line

int a= 1;

switch (a) {
case 1: System.out.println(“ONE”);
break;
case 7: System.out.println(“SEVEN”);
break;
case 2: System.out.println(“THREE”);
break;
}
Output :
ONE
© Dr. Jonathan Cazalas Chapter 3: Selections page 105
animation

Trace switch statement (break)


Execute next statement

int a= 1;

switch (a) {
case 1: System.out.println(“ONE”);
break;
case 7: System.out.println(“SEVEN”);
break;
case 2: System.out.println(“THREE”);
break;
}
Next statement;
© Dr. Jonathan Cazalas Chapter 3: Selections page 106
animation

Trace switch statement (default)


int a= 10; Execute this line

switch (a) {
case 1: System.out.println(“ONE”);
break;
case 7: System.out.println(“SEVEN”);
break;
case 2: System.out.println(“THREE”);
break;
default :
System.out.println(“ERROR”);
}
Pay attention:
Output : Here, we used the default option,
ERROR which is used for any case not listed.

© Dr. Jonathan Cazalas Chapter 3: Selections page 107


animation

Trace switch statement


char ch = ‘a’;

switch (ch) {
case 'a': System.out.println(ch);
case 'B': System.out.println(ch);
case 'c': System.out.println(ch);
}

© Dr. Jonathan Cazalas Chapter 3: Selections page 108


animation

Trace switch statement

ch is 'a':

char ch = ‘a’;

switch (ch) {
case 'a': System.out.println(ch);
case 'B': System.out.println(ch);
case 'c': System.out.println(ch);
}

© Dr. Jonathan Cazalas Chapter 3: Selections page 109


animation

Trace switch statement


Execute this line

switch (ch) {
case 'a': System.out.println(ch);
case 'B': System.out.println(ch);
case 'c': System.out.println(ch);
}
Output :
a

© Dr. Jonathan Cazalas Chapter 3: Selections page 110


animation

Trace switch statement


Execute this line

switch (ch) {
case 'a': System.out.println(ch);
case 'B': System.out.println(ch);
case 'c': System.out.println(ch);
}
Output :
a
a

© Dr. Jonathan Cazalas Chapter 3: Selections page 111


animation

Trace switch statement


Execute this line

switch (ch) {
case 'a': System.out.println(ch);
case 'B': System.out.println(ch);
case 'c': System.out.println(ch);
}
Output :
a
a
a

© Dr. Jonathan Cazalas Chapter 3: Selections page 112


animation

Trace switch statement


Execute next statement

switch (ch) {
case 'a': System.out.println(ch);
case 'B': System.out.println(ch);
case 'c': System.out.println(ch);
}

Next statement;

© Dr. Jonathan Cazalas Chapter 3: Selections page 113


animation

Trace switch statement


Suppose ch is 'a':

switch (ch) {
case 'a': System.out.println(ch);
break;
case 'B': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}

© Dr. Jonathan Cazalas Chapter 3: Selections page 114


animation

Trace switch statement


ch is 'a':

switch (ch) {
case 'a': System.out.println(ch);
break;
case 'B': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}

© Dr. Jonathan Cazalas Chapter 3: Selections page 115


animation

Trace switch statement


Execute this line

switch (ch) {
case 'a': System.out.println(ch);
break;
case 'B': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
Output :
a

© Dr. Jonathan Cazalas Chapter 3: Selections page 116


animation

Trace switch statement


Execute this line

switch (ch) {
case 'a': System.out.println(ch);
break;
case 'B': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}
Output :
a

© Dr. Jonathan Cazalas Chapter 3: Selections page 117


animation

Trace switch statement


Execute next statement

switch (ch) {
case 'a': System.out.println(ch);
break;
case 'B': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}

Next statement;

© Dr. Jonathan Cazalas Chapter 3: Selections page 118


animation

Trace switch statement


Suppose day is 2:

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

119 page 119


© Dr. Jonathan Cazalas Chapter 3: Selections
animation

Trace switch statement


Match case 2

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

120 page 120


© Dr. Jonathan Cazalas Chapter 3: Selections
animation

Trace switch statement


Fall through case 3

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

121 page 121


© Dr. Jonathan Cazalas Chapter 3: Selections
animation

Trace switch statement


Fall through case 4

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

122 page 122


© Dr. Jonathan Cazalas Chapter 3: Selections
animation

Trace switch statement


Fall through case 5

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

123 page 123


© Dr. Jonathan Cazalas Chapter 3: Selections
animation

Trace switch statement


Encounter break

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

124 page 124


© Dr. Jonathan Cazalas Chapter 3: Selections
animation

Trace switch statement


Exit the statement

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}

125 page 125


© Dr. Jonathan Cazalas Chapter 3: Selections
Write a switch statement that displays Sunday,
Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday if day is 0, 1, 2, 3, 4, 5, 6, respectively.
– Solution:
switch (day) {
case 0: System.out.println(“Sunday”); break;
case 1: System.out.println(“Monday”); break;
case 2: System.out.println(“Tuesday”); break;
case 3: System.out.println(“Wednesday”); break;
case 4: System.out.println(“Thursday”); break;
case 5: System.out.println(“Friday”); break;
case 6: System.out.println(“Saturday”); break;
}

© Dr. Jonathan Cazalas Chapter 3: Selections page 126


Conditional Expressions
You may want to assign a value to a variable
based off of certain conditions
Example:
– The following statement assigns 1 to y if x > 0, and it
assigns -1 to y if x <= 0.
– Code:
if (x > 0)
y = 1;
else
y = -1;

© Dr. Jonathan Cazalas Chapter 3: Selections page 127


Conditional Expressions
The last code works just fine
But you can use a conditional expression to
achieve the same result:
y = (x > 0) ? 1 : -1;
The generic syntax is as follows:
boolean-expression ? expression1 : expression2;

The result of this conditional expression is


expression1 if boolean-expression is true;
otherwise, the result is expression2.

© Dr. Jonathan Cazalas Chapter 3: Selections page 128


Conditional Expressions
Example:
– Given two numbers, num1 and num2, save the larger
into a variable called max.
– You can do this with an if/else statement
if (num 1 > num2)
max = num1;
else
max = num2;
– Or you can use one conditional expression as follows:
max = (num1 > num2) ? num1 : num2;

© Dr. Jonathan Cazalas Chapter 3: Selections page 129


Conditional Expressions
Example:
– Given a variable, num, display the message “num is
even” if num is even; otherwise, display “num is odd”
– You can do this with an if/else statement
if (num % 2 == 0)
System.out.println(“num is even”);
else
System.out.println(“num is odd”);
– Or you can use one conditional expression as follows:
System.out.println((num % 2 == 0) ?
“num is even” : “num is odd”);

© Dr. Jonathan Cazalas Chapter 3: Selections page 130


Rewrite the following if statements using the conditional
operator.
if (ages >= 16)
ticketPrice = 20;
else
ticketPrice = 10;

– Solution:

ticketPrice = (ages >= 16) ? 20 : 10;

© Dr. Jonathan Cazalas Chapter 3: Selections page 131


Operator Precedence
Chapter 2 introduced operator precedence
involving arithmetic operators
– Example:
* and / has higher precedence than + and –
But what about expressions with other operators
– Example:
3 + 4 * 4 > 5 * (4 + 3) – 1 && (4 – 3 > 5)
– What is the value? What is the execution order of the
above example?
– We need to know the precedence rules for this!
© Dr. Jonathan Cazalas Chapter 3: Selections page 132
Operator Precedence

© Dr. Jonathan Cazalas Chapter 3: Selections page 133


Operator Precedence
Details:
– The expression in the parentheses is evaluated first.
– Parentheses can be nested, in which case the
expression in the inner parentheses is executed first.
– When evaluating an expression without parentheses,
the operators are applied according to the precedence
rule and the associativity rule.
– If operators with the same precedence are next to each
other, their associativity determines the order of
evaluation. All binary operators except assignment
operators are left-associative.
© Dr. Jonathan Cazalas Chapter 3: Selections page 134
Operator Precedence
Details:
– Example:
+ and – are of the same precedence and are left associative
Therefore,

– Example:
Assignment operators are right associative
Therefore,

© Dr. Jonathan Cazalas Chapter 3: Selections page 135


Debugging
Dealing with programming errors
– Remember: syntax errors and runtime errors are not
difficult to find
– However, logic errors can be very challenging
– Logic errors are called bugs
– Debugging is the process of finding and corrected
these logic errors

© Dr. Jonathan Cazalas Chapter 3: Selections page 136


Debugging
Methods of debugging:
– You can hand-trace the program
Meaning, you try to find the error by reading the program
Clearly, this is very difficult and time consuming
– You can insert print statements throughout the
program
The print statements allow you to see how far the execution
has reached
You can also print, and then view, the values of variables
during execution of the program.
Again, this is time consuming
© Dr. Jonathan Cazalas Chapter 3: Selections page 137
Debugging
Methods of debugging:
– These two methods are okay, but they are slow.
They really only work for small, simple programs
– So what about large, complex programs?
– The best solution is to use a debugger utility

All Java IDE programs, such as Eclipse and


NetBeans, include integrated debuggers.
– Learning how to use these debuggers is very
important.
© Dr. Jonathan Cazalas Chapter 3: Selections page 138
Debugging
Debugger is a program that facilitates debugging.
You can use a debugger to
–Execute a single statement at a time.
–Trace into or stepping over a method.
–Set breakpoints.
–Display variables.
–Display call stack.
–Modify variables.

© Dr. Jonathan Cazalas Chapter 3: Selections page 139

You might also like