Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Conditional statements

•  Within a method, we can alter the flow of control


(the order in which statements are executed)
using either conditionals or loops.
Conditional Statements
•  The conditional statements if, if-else, and
switch allow us to choose which statement will
be executed next.
15-110 Summer 2010
•  Each choice or decision is based on the value of
Margaret Reid-Miller
a boolean expression (also called the condition).

Summer 2010 15-110 (Reid-Miller) 2

The if statement The if Flowchart


•  If we have code that we sometimes want to execute
and sometimes we want to skip we can use the if
statement. false
•  The form of the if statement is boolean_expression
if (boolean_expression)
statement true

•  If boolean_expression evaluates to true, then statement


statement is executed.
•  If boolean_expression evaluates to false, then
statement is skipped.
•  Note that the boolean_expression enclosed in
parentheses must evaluate to true or false.
Summer 2010 15-110 (Reid-Miller) 3 Summer 2010 15-110 (Reid-Miller) 4
if-Statement Examples The if Statement
!if (count > 0) ! •  The statement in the if statement can be any Java
average = total / count;! statement:
Or simply •  A simple statement
if (age >= 26) ! hasLicense
•  A compound statement, such as an if statement
!if (hasLicense == true)!
!System.out.println(“You may rent a car.”);!
•  A block statement, a group of statements
enclosed in braces {}
daysInFeb = 28;!
! if (isLeapYear) {! if (zipcode == 15213) {!
Proper indentation
daysInFeb = 29;! city = “Pittsburgh”;!
becomes essential!
System.out.println(year + “ is a leap year.”);! state = “PA”;!
}! }!
Summer 2010 15-110 (Reid-Miller) 5 Summer 2010 15-110 (Reid-Miller) 6

The if-else Statement The if-else Flowchart


•  If we want to choose between two alternative we use
the if/else statement:
if (boolean_expression)! true false!
statement1! boolean_expression
else !
! statement2!
•  If boolean_expression evaluates to true, then statement1 statement2
statement1 is executed.
•  If boolean_expression evaluates to false, then
statement2 is executed.

Summer 2010 15-110 (Reid-Miller) 7 Summer 2010 15-110 (Reid-Miller) 8


if-else Statement Examples Common Error 1
!if (temperature <= 32.0) {! •  When you want to test if the value of a
! forecast = “SNOW”; ! The then clause variable is in a range.
!} !
else {!
forecast = “RAIN”;! The else clause !if (0 < temperature < 100) { !
!}
WRONG!!
! state = “LIQUID”; !
!}!
!if (count > 0) { !
! average = total / count; ! if (0 < temperature && temperature < 100) { !
!} ! !state = “LIQUID”; !
else {!
Correct
}!
! System.out.println(“No data to average.”);!
!}
Summer 2010 15-110 (Reid-Miller) 9 Summer 2010 15-110 (Reid-Miller) 10

Common Error 2 The Dangling else Problem


•  When you want to test if the value of a •  When an if statement is nested inside the then
variable is one of two alternates. clause of another if statement, the else clause is
paired with the closest if statement without an else
clause.
!if (choice == ‘M’ || ‘L’) { ! WRONG!!
if (x > 0) !
! System.out.println(“You’re correct!”); !
if (y > 0)!
!}!
color = “red”; !
else !
Misleading
if (choice == ‘M’ || choice == ‘L’) { !
color = “blue”; indentation
! System.out.println(“You’re correct!”); !
}! Correct

Summer 2010 15-110 (Reid-Miller) 11 Summer 2010 15-110 (Reid-Miller) 12


The Dangling else Problem The Dangling else Problem
•  In reality it is •  Use braces to pair else
y y
if (x > 0) ! with the outer if
if (y > 0)! if (x > 0) {!
color = “red”; ! if (y > 0)!
else ! color = “red”; !
color = “blue”; } !
x else {! x
color = “blue”;!
}!

•  Compare flowcharts!

Summer 2010 15-110 (Reid-Miller) 13 Summer 2010 15-110 (Reid-Miller) 14

Multiple Alternatives Multiple Alternatives


•  Determine if a number is positive, negative, or zero: •  Determine if a number is positive, negative, or zero
if (value < 0) {!
! System.out.println(“Value is negative.”);!
if (value < 0) {! } !
!System.out.println(“Value is negative.”);! else {!
} ! ! if (value == 0) {!
! ! System.out.println(“Value is zero.”);!
if (value == 0) {!
! } !
!System.out.println(“Value is zero.”);! else {!
}! ! ! if (value > 0) {!
if (value > 0) {! ! ! ! System.out.println(“Value is positive.”);!
!System.out.println(“Value is positive.”);! ! ! }!
! }! At most one statement is executed.
}! Computer thinks any combination of }! Leads to lots of indentation.
the three statements can be executed.
Summer 2010 15-110 (Reid-Miller) 15 Summer 2010 15-110 (Reid-Miller) 16
Multiple Alternatives Multiple Alternatives
•  Determine if a number is positive, negative, or zero •  Determine if a number is positive, negative, or zero:
if (value < 0) {!
! System.out.println(“Value is negative.”);! if (value < 0) {!
} ! ! System.out.println(“Value is negative.”);!
else {! } !
! if (value == 0) {! else if (value == 0) {!
! ! System.out.println(“Value is zero.”);! ! !System.out.println(“Value is zero.”);!
! } ! } !
else {! else if (value > 0) {!
! ! if (value > 0) {!
! !System.out.println(“Value is positive.”);!
! ! ! System.out.println(“Value is positive.”);!
}!
! ! }!
At most one statement is executed.
! }! Remove unnecessary
Each choice, however, is at same indentation.
brackets and re-indent
}!
Summer 2010 15-110 (Reid-Miller) 17 Summer 2010 15-110 (Reid-Miller) 18

Multiple Alternatives Multiple Alternatives: Assignments


•  Determine if a number is positive, negative, or zero: •  Determine the fare: $2 for a child (no more than 11
years), $3 for a senior (at least 65 years), or $5 for an
if (value < 0) {! adult.
fare must be defined
int fare;!
!System.out.println(“Value is negative.”);! before the if statement
} ! if (age _______) {!
!fare = 2;!
else if (value == 0) {!
} !
! !System.out.println(“Value is zero.”);!
else if (age __________) { // _____________________!
} ! !fare = 5;!
else { // value must be positive! } !
! !System.out.println(“Value is positive.”);! else { // ________________! last clause must be
}! !fare = 3;! else with no if
It is clear, exactly one statement is executed. }!
System.out.println(“Your fare is $“ + fare);!

Summer 2010 15-110 (Reid-Miller) 19 Summer 2010 15-110 (Reid-Miller) 20


Exercise Exercise
•  Write a method that prints how many of n1, n2, and •  Write a method that print whether die1 and die2 are
n3 are odd: doubles, cat’s eyes (two 1’s) or neither of these.
public void printNumOdd(int n1, int n2, int n3) {! public void printDoubles(int die1, int die2) {!

}!
Summer 2010 15-110 (Reid-Miller) 21 Summer 2010 15-110 (Reid-Miller) 22

Programming Style Testing For Equality


•  Single-line if statement: if (y > 0) color = “red”;!
•  For primitive values use == for equality testing.
•  Multi-line if statement: if (zipcode == 15213) {!
city = “Pittsburgh”;! •  For objects, use the equals method for testing
state = “PA”;!
} equal contents.
•  The argument must be the same type as the object on which
•  The if-else statement: if (temperature <= 32.0) {!
forecast = “SNOW”; ! equals() is called. The method returns true or false
} ! depending on whether both objects are “equal” or not.
else {!
forecast = “RAIN”;!
}! •  For example, let day be an int variable and month
•  Multiple alternatives: if (value < 0) {!
valueType = “negative”;!
be a String variable.
} ! ! if (day == 1 && month.equals(“APRIL”)) {!
else if (value == 0) {!
valueType = “zero”;! ! System.out.println(“It’s April Fool’s Day”);!
} ! }
else { // no if here!!!
valueType = “positive”;! Two String objects are equal if they have exactly the same
}! characters, including case and number of characters.

Summer 2010 15-110 (Reid-Miller) 23 Summer 2010 15-110 (Reid-Miller) 24


Testing for Equality with doubles Testing for Equality with doubles
•  Which statement will Java print? •  Because of round-off errors, you should test if the
numbers are close.
double x = Math.sqrt(2.0);!
double y = x * x;! double tolerance = 1.0e-10;
double x = Math.sqrt(2.0);!
double y = x * x; !
if (y == 2.0) {!
!System.out.println("sqrt(2) * sqrt(2) is 2");! if (Math.abs(y - 2.0) < tolerance) {!
} ! !System.out.println("sqrt(2) * sqrt(2) is 2");!
else {! } !
!System.out.println("sqrt(2) * sqrt(2) “! else {!
! ! ! !+ “is not 2. It is " + y);! !System.out.println("sqrt(2) * sqrt(2) “!
} ! ! ! !+ “is not 2. It is " + y);!
Never test for exact equality }!
with floating point numbers!
Summer 2010 15-110 (Reid-Miller) 25 Summer 2010 15-110 (Reid-Miller) 26

Short-Circuit Evaluation The switch statement


•  Short circuit evaluation (or lazy evaluation) : If the first •  If an if/else statement with multiple alternatives
conditional in an && expression is false, Java does compares an int or char variable or expression
not execute the second conditional. against several constants you can use a switch
statement.
Example: Example:
! if (liters > 0 && total/liters > threshold) {! !switch (suitAsChar) {!
! System.out.println(“WARNING: Exceeds threshold”);! !case ‘C’: suitAsName = “Clubs”; break;!
} !case ‘D’: suitAsName = “Diamonds”; break;!
!case ‘H’: suitAsName = “Hearts”; break;!
!case ‘S’: suitAsName = “Spades”; break;!
What if the expression was an || expression? !default: suitAsName = “Unknown”;!
}!

Summer 2010 15-110 (Reid-Miller) 27 Summer 2010 15-110 (Reid-Miller) 28


The for Loop
•  Another loop statement, for, is best for when you
can determine in advance how many times you need
to execute the loop (counting loop).
For Loops
•  The for statement includes the three parts needed
for loops: initialize, test, and update.
15-110 Summer 2010 •  All this information is conveniently placed at the
beginning of the loop.
Margaret Reid-Miller
•  All three loop statements (while, do, and for) are
functionally equivalent.

Summer 2010 15-110 (Reid-Miller) 2

The for statement The for statement


•  The form of the for statement is •  The form of the for statement is
for (<initialize>; <boolean_expression>; <update>) for (<initialize>; <boolean_expression>; <update>)
<statement> <statement>

•  First, the initialize statement is executed. •  It is equivalent to


•  If boolean_expression evaluates to true, then
statement (body of loop) is executed, followed by the <initialize>;
update statement. while (<boolean_expression>) {
<statement>
•  The loop repeats until the boolean_expression
evaluates to false. <update>; executed after
} statement
(body of loop)
Summer 2010 15-110 (Reid-Miller) 3 Summer 2010 15-110 (Reid-Miller) 4
The for Flowchart A for Loop Example
initialize n=4
!int sum = 0;! sum i
!for (int i = 1; i <= n; i++) {! 0
false ! !sum += i*i;! 1
boolean_expression i <= n ?
!}! 1
!System.out.println(sum);!
2
update true i <= n ?
5
Which variable is the loop
3
statement control variable? i <= n ?
14
(body of loop)
4
i <= n ?
30
5
i <= n ?
Summer 2010 15-110 (Reid-Miller) 5 Summer 2010 15-110 (Reid-Miller) 6

Another for Loop Example Scope


n = 11
sum i •  The scope of a variable is the area within a program that
!int sum = 0;! 0 can reference the variable.
!for (int i = 1; i <= n; i+=3) {! 1 •  The scope depends on where the variable is declared.!
! !sum += i;! i <= n ?
1
!}! !int sum = 0;!
4
!System.out.println(sum);! i <= n ? !for (int i = 1; i <= n; i++) {!
5 Scope of
! !sum += i*i;!
7 !}!
variable i
i <= n ?
12 !System.out.println(sum);!
10
i <= n ?
22
13
i <= n ?
Summer 2010 15-110 (Reid-Miller) 7 Summer 2010 15-110 (Reid-Miller) 8
Scope Nested Loops
!int sum = 0;! •  A loop can have another loop inside of it.
!int i;! •  For each iteration of the outside loop, the inside loop
!for (i = 1; i <= n; i++) {! runs completely.
! !sum += i*i;! Scope of •  Often it is easiest to read from the inside out.
!}! variable i •  Example:
!System.out.println(“Sum of first “ + (i-1)!
! + “ integers squared is “ + sum);! How many lines are printed?
for (int i = 1; i <= 5; i++) {!
for (int j = 1; j <= 3; j++) {!
System.out.println(i + " " + j);!
}!
} What happens if we
write println(i + j)?
Summer 2010 15-110 (Reid-Miller) 9 Summer 2010 15-110 (Reid-Miller) 10

Palindromes Which Loops?


•  A palindrome is word, phrase, or sequence that reads •  for loops are more natural when we know how many
the same backwards as forwards. iterations we need (definite or counting loops).
Examples:
•  Example: Bob by Weird Al Yankovic •  Print "*" 10 times
•  Print the even numbers between 10 and the value of n
(A parody of Bob Dylan's Subterranean Homesick
Blues) •  while and do loops are more natural when we want
to keep looping until some outcome (indefinite or
result controlled loops).
http://www.youtube.com/watch?v=Nej4xJe4Tdg
Examples:
•  Prompt the user until the user inputs the data in the correct
How would you test whether a string is a palindrome? form.
•  Continue looping until we reached a million dollars.
Summer 2010 15-110 (Reid-Miller) 11 Summer 2010 15-110 (Reid-Miller) 12
Loops
•  Within a method, we can alter the flow of control
using either conditionals or loops.
•  The loop statements while, do-while, and for
While and Do-While Loops allow us execute a statement(s) over and over.
•  Like a conditional, a loop is controlled by a boolean
expression that determines how many times the
15-110 Summer 2010 statement is executed.
Margaret Reid-Miller
E.g., You may want to calculate the interest paid on a mortgage
for each year of the loan term.

Summer 2010 15-110 (Reid-Miller)

The while statement The if Flowchart


•  The form of the while statement is
while (<boolean_expression>)
<statement> false
boolean_expression
•  If boolean_expression evaluates to true, then
statement is executed. true
•  Then, the boolean_expression is evaluated again. If statement
it evaluates to true, statement is executed again. (body of loop)
•  This repetition continues until the
boolean_expression evaluates to false.

How is the while loop different from the if statement?


Summer 2010 15-110 (Reid-Miller) Summer 2010 15-110 (Reid-Miller)
n=5
The while Flowchart A while Example i output
0
Print n asterisks! i<n?
*!
1
false int i = 0; ! i<n?
boolean_expression while (i < n) { ! ! **!
System.out.print(“*”);! 2
i<n?
true !i++;! ***!
}! 3
statement i<n?
(body of loop) System.out.println();! ****!
4
i<n?
*****!
5
i<n?
*****

Summer 2010 15-110 (Reid-Miller) Summer 2010 15-110 (Reid-Miller)

The Loop Control Variable Off-by-1 Errors


•  The variable i (known as the loop control variable)
is used in three ways: it is initialized, tested, and
int i = 0; ! !int i = 1; !
updated.!
while (i < n) { ! ! !while (i < n) {!
!int i = 0; ! // initialize System.out.print(“*”);! ! !System.out.print
!while (i < n) {! // test !i++;! (“*”);!
!! System.out.print(“*”);! }! ! !i++;!
!! i++;! // update System.out.println();! !}!
!}! !System.out.println();!
!System.out.println();! For n = 5 the output is
***** (5 asterisks) Output?
•  All three things must be coordinated in order for
the loop to work correctly!
Summer 2010 15-110 (Reid-Miller) Summer 2010 15-110 (Reid-Miller)
Off-by-1 Errors Warning!

int i = 0; ! !int i = 0; ! int i = 0; ! !What is the output if n = 5?


while (i < n) { ! ! !while (i <= n) {! while (i < n) {!
System.out.print(“*”);! ! !System.out.print ! !
!i++;! (“*”);! System.out.print(“*”);!
}! ! !i++;! !i--;!
System.out.println();! !}! }!
!System.out.println();! System.out.println();!
For n = 5 the output is
***** (5 asterisks) Output?

Summer 2010 15-110 (Reid-Miller) Summer 2010 15-110 (Reid-Miller)

Infinite Loops A while Example

Do you know which


int i = 0; ! int i = 0; ! !What is the output if n = 0?
while (i < n) {!
company has this address? while (i < n) { ! !
! ! System.out.print(“*”);!
System.out.print(“*”);! Apple Computer !i++;!
!i--;! }!
1 Infinite Loop
}! System.out.println();!
Cupertino, CA 95014
System.out.println();!

Summer 2010 15-110 (Reid-Miller) Summer 2010 15-110 (Reid-Miller)


Exercise Exercise: Cumulative Sum
•  Write a method with a while loop to prints 1 through •  Write a method with a while loop that computes the
n in square brackets. For example, if n = 6 print sum of first n positive integers:
! ![1] [2] [3] [4] [5] [6]! sum = 1 + 2 + 3 + … + n

Examples:
n=5 sum = 15

n = 19 sum = 190

Summer 2010 15-110 (Reid-Miller) Summer 2010 15-110 (Reid-Miller)

Exercise: Fencepost Loop The do Statement


•  Write a method with a while loop that prints 1 •  The form of the do statement is
through n, separated by commas. E.g., for n = 9 print do!
1, 2, 3, 4, 5, 6, 7, 8, 9! <statement>
! !while (<boolean_expression>);

•  First, statement is executed.


•  Then, the boolean_expression is evaluated. If it
evaluates to true, statement is executed again.
•  This repetition continues until the
boolean_expression evaluates to false.

Summer 2010 15-110 (Reid-Miller) Summer 2010 15-110 (Reid-Miller)


The do Flowchart Example

!int i = 0; // initialize!
!do {!
statement !! System.out.print(“*”); !
!! i++; // update!
true !} while (i < n); // test!
!System.out.println();!
boolean_expression

false For n = 7 what is the output?


How is it different from the while loop?

Summer 2010 15-110 (Reid-Miller) Summer 2010 15-110 (Reid-Miller)

User Input User Input (cont’d)


•  Use a do-while loop to test whether a user has entered
Scanner keyboard = new Scanner(System.in);! data of the correct form and, if not, ask repeatedly until
System.out.print(! the data entered is correct.
! !“Please enter the month [1-12]: ”);!
int month = keyboard.nextInt();! Scanner keyboard = new Scanner(System.in);!
int month;! Must be declared
do {! outside the loop
What if the user enters a month outside the range? !System.out.print(!
!!“Please enter the month [1-12]: ”);!
!month = keyboard.nextInt();!
} while ( month < 1 || month > 12 );!
Outside the scope
of the loop
Summer 2010 15-110 (Reid-Miller) Summer 2010 15-110 (Reid-Miller)
User Input Sentinel Controlled Loops
•  Sometimes it is easier to think of what you want the •  Suppose you want to find the maximum of the data
input to be and negate. entered from the keyboard.
•  It is not known in advanced how many data values a
Scanner keyboard = new Scanner(System.in);! user might want to enter. (And the user may not want
int month;!
What is the to count them!)
do {!
!System.out.print(! loop control •  A sentinel is a special value that is used to detect a
! variable?
!“Please enter the month [1-12]: ”);! special condition, in this case that the user is done
!month = keyboard.nextInt();! entering values.
} while (!(month >= 1 && month <= 12));! •  The sentinel, of course, must be distinct from any value
the user may want to input.
Use de Morgan’s law to prove the Boolean expressions are the same!

Summer 2010 15-110 (Reid-Miller) Summer 2010 15-110 (Reid-Miller)

Sentinel Example
Scanner console = new Scanner(System.in);!
System.out.print(“Enter count (enter -1 to quit): “);!
int count = console.nextInt();!
int maxSoFar = count;! Consider making -1
a named constant
while (count != -1) {!
if (count > maxSoFar) maxSoFar = count;

System.out.print(“Enter count (enter -1 to quit): “);!


count = console.nextInt();!
}!

if (maxSoFar > -1) !


!System.out.println(“The maximum is “ + maxSoFar);!
else !
!System.out.println(“No counts entered”);

Summer 2010 15-110 (Reid-Miller)

You might also like