COMP 248:
OBJECT ORIENTED PROGRAMMING I
Compound statements, nesting, switch, while
The content on these slides was provided by Dr.
Nora Houari.
Contents
5. Compound statements
6. Nested if statements
7. The switch statement
8. The conditional operator
9. The while loop
2
5- Compound statements
So far have seen
if ( condition ) if ( condition )
statement; statement1;
else
statement2;
What if you wanted to execute several statements?
3
5- Compound statements …
Several statements can be grouped together into a compound
statement (or block):
{
statement1;
statement2;
…
}
A block can be used wherever a statement is called for by the Java
syntax
4
Example – Output?
int grade;
System.out.print("what is your grade?");
grade = myKeyboard.nextInt();
if (grade >= 80)
System.out.println("congratulations!");
else
System.out.println("you could do better");
System.out.println("make sure you practice");
System.out.println("bye bye");
5
6 - Nested if statements
An if is a statement… so we can put an if “inside” an if
Called nested if statements
if ( condition1 )
if(condition2 )
statement;
else
statement;
6
Nested if statements …
if ( condition1 )
{
if(condition2 )
statement1;
statement2;
}
7
Nested if statements …
if ( condition1 )
if(condition2 )
{
statement1;
statement2;
}
else
statement;
8
Output/Trace
int num1, num2, num3, min = 0;
System.out.println ("Enter three integers: ");
num1 = keyboard.nextInt();
num2 = keyboard.nextInt();
num3 = keyboard.nextInt();
if (num1 < num2)
if (num1 < num3)
min = num1;
else
min = num3;
else
if (num2 < num3)
Trace
min = num2;
else
min = num3;
System.out.println ("Minimum value: " + min); 9
Just checking …
Given the following code segment, what is stored in a at the end of
this sequence?
int a = 0; A. 0
if (a >= 10) B. 1
if (a < 20)
C. 2
a = a + 2;
else D. 3
a = a + 1; E. Syntax error
See why indenting makes it easier to read code!
10
Dangling else
An else clause is matched to the last unmatched if
(no matter what the indentation implies)
if (condition1)
if (condition1)
if (condition2) {
statement1; if (condition2)
else
statement1;
statement2;
}
else
statement2;
11
Example: Leap year
Problem:
Leap years occur in years exactly divisible by four, except that years ending in 00
are leap years only if they are divisible by 400.
Examples
• 1700, 1800, 1900, 2100, and 2200 are not leap years
• 1600, 2000, and 2400 are leap years.
Algorithm:
• if year is a multiple of 400 --> leap
• otherwise
if year is a multiple of 100 --> not leap
otherwise
– if year is a multiple of 4 --> leap
– otherwise --> not leap
12
Code
13
7- The switch statement
Remember: Java's conditional statements are
– the statement
– the statement
– the switch statement
The switch:
– replaces a series of if-else-if-else-if-else…
– like a multiple-choice question
– that tests the equality of an expression
– the expression must evaluate to a char, int, short, or
byte
14
Example 1 using nested if statements
char romanNumeral;
int decValue; Switch statement provides
if (romanNumeral == 'I')
decValue = 1; a cleaner way to do
else if (romanNumeral == 'V') multiway selection than the
decValue = 5; more general nested if.
else if (romanNumeral == 'X')
decValue = 10;
else if (romanNumeral == 'L')
decValue = 50;
else if (romanNumeral == 'C')
decValue = 100;
else
System.out.println( "Not a Roman numeral <= 100“);
15
Example 1 Using Switch
char romanNumeral; int decValue;
switch(romanNumeral)
{
case 'I': decValue = 1;
break;
case 'V': decValue = 5;
break;
case 'X': decValue = 10;
break;
case 'L': decValue = 50;
break;
case 'C': decValue = 100;
break;
default: System.out.println( "Not a Roman numeral<= 100 “);
} 16
The switch statement
syntax: switch ( expression )
{
switch, case value1 :
case, statement-list1
break, break;
default case value2 :
are reserved statement-list2
words break;
case value3 :
statement-list3 If expression
break and break; matches value2,
default case ... control jumps
case default: to here
are optional default-statement-list
}
17
More on the switch
break
– Often used as the last statement in each case
– break causes control to transfer to the end of the switch
– If a break is not used, the flow of control will continue into the
next case
default case
– A switch can have an optional default case
– If the default case is present, control will transfer to it if no
other case value matches
– the default case can be positioned anywhere in the switch, but
usually it is placed at the end
18
Logic of the switch
1. The expression is evaluated
2. Its value is compared to the various cases
3. If an equality is found, the corresponding statements are
executed until a break or until the end of the switch
4. If no equality is found, the default statements are executed if a
default case is there.
19
Example 2
int grade, category;
System.out.print("Enter a grade (0 to 100):"); If user enters 100?
grade = keyboard.nextInt();
category = grade / 10;
switch (category) {
case 10: case 9:
System.out.println ("excellent.");
break; Output
case 8:
System.out.println ("nice job.");
break;
case 7:
System.out.println ("average.");
break;
case 6:
System.out.println ("below average.");
break;
default:
System.out.println ("problem.");
} 20
What about…
int grade, category;
System.out.print("Enter a grade (0 to 100):"); If user enters 94?
grade = keyboard.nextInt();
category = grade / 10; A. excellent
switch (category) { B. excellent
case 10: case 9:
nice job
System.out.println ("excellent.");
break; C. excellent
case 8: nice job
System.out.println ("nice job."); average
break;
D. excellent
case 7:
System.out.println ("average."); nice job Output
break; average
case 6:
below average
System.out.println ("below average.");
break; E. None of the above
default: choices
System.out.println ("problem.");
} 21
What about…
int grade, category; If user enters 57?
System.out.print("Enter a grade (0 to 100):");
grade = keyboard.nextInt(); A. excellent
category = grade / 10;
switch (category) { B. excellent
nice job
case 10: case 9:
System.out.println ("excellent.");
break; C. excellent
nice job Output
case 8: average
System.out.println ("nice job.");
break;
D. excellent
case 7:
System.out.println ("average."); nice job
break; average
below average
case 6:
System.out.println ("below average.");
break; E. None of the above
choices
default:
System.out.println ("problem.");
} 22
Example 3
Transform the previous switch into a if-else statement
23
8- The conditional operator
Shortcut to an if in some cases
ternary operator (needs 3 operands)
Syntax : condition ? expression1 : expression2
Semantics:
– if the condition is true, expression1 is evaluated;
– if it is false, expression2 is evaluated
– the result of the chosen expression is the result of the entire
conditional operator
24
Example
larger = ((num1 > num2) ? num1 : num2);
System.out.println(larger);
If num1 is 10 and num2 is 20 ? Output
If num1 is 20 and num2 is 10 ?
25
Example
System.out.println("Change is " + count +((count==1) ?
" Dime": " Dimes"));
If count is 1?
If count is not 1?
Output
26
Repetition statements (loops)
Allow us to execute a statement several times
Like conditional statements, they are controlled by boolean
expressions
Java has 3 kinds of loops:
– the while loop
– the do loop
– the for loop
27
Shampoo Algorithm: Version 1
Wet Hair
Pour
Lather
Rinse
Repeat
Dry Hair
What is wrong with this algorithm?
Shampoo Algorithm: Version 2
Wet Hair
while Hair is dirty
Pour Shampoo
Lather
Rinse
Dry Hair http://www.majorlycool.com/media/1/20080119-Xie-
Qiuping-Washing-Hair.jpg
Better….
but what is wrong with this algorithm?
Shampoo Algorithm: Version 3
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
Wet Hair
while (Hair is dirty and _ _ _ _ _ _ _ _ _ )
Pour Shampoo
Lather
Rinse
_ _ _ _ _ _ _ _ _ _ =_ _ _ _ _ _ _ _ _ _ _ _ _ _
Dry Hair
9- The while loop
syntax:
while ( condition )
while is a
statement;
reserved word
If the condition is true, the statement is executed.
Then the condition is evaluated again.
The statement is executed repeatedly until
the condition becomes false.
31
Logic of a while loop
condition
evaluated
true false
statement
32
The while loop
Note that if the condition of a while statement is false
initially, the statement is never executed
So, the body of a while loop will execute zero or more times
final int LIMIT = 5;
LIMIT count
int count = 1;
while (count <= LIMIT) Trace
{
System.out.println(count);
count = count + 1;
}
Output
System.out.println("Done");
33
Example 1
int remainingStars = 5; int remainingStars = 5;
while (remainingStars > 0) while (remainingStars > 0)
{ System.out.println("*");
System.out.println("*"); remainingStars--;
remainingStars--;
}
remainingStars remainingStars
Trace Trace
Output Output
34
Example 2
public class Forever
count
{
public static void main (String[] args)
{ Trace
int count = 1;
while (count <= 10)
{
System.out.println (count);
count = count - 1;
}
System.out.println("Done");
}
}
Output
35
What is output?
int index = 1;
while (index != 10)
{
System.out.print("Hello");
index = index + 2;
}
A. There will be no output, since index is not equal to 10
B. HelloHelloHelloHello
C. HelloHelloHelloHelloHello
D. HelloHelloHelloHelloHelloHello
E. None of the above are correct choices
36
Just checking?
The termination condition for the while loop
int w loopCount = 0;
while (loopCount < 9)
{
System.out.print(loopCount);
loopCount++;
}
is loopCount > 9.
A. true
B. false
C. Syntax error
37
What is output?
boolean finished = false; A. 3
int firstInt = 3;
B. 5
int secondInt = 20;
C. 7
while (firstInt <= secondInt && !finished)
D. 8
if (secondInt / firstInt <= 2)
E. 9
finished = true;
else
firstInt++;
System.out.println(firstInt);
38
Example 3: Compute average
Enter a series of marks (negative number to quit):
80.5 70 67 53.8 -1
The average is: 67.825
Data needed:
Algorithm:
39
Example 3: Averager.java
40
Example 4: max and min
same thing… but now, determine the highest and lowest
marks too.
Data needed:
Algorithm:
41
Example 4: max and min (code)
42