SLIDE 2
What did we talk about last time? if statements else statements Nested selection statements
SLIDE 3
SLIDE 4
SLIDE 5
SLIDE 6
The if part Any boolean expression Executable statements
if( condition ){ statements; }
SLIDE 7 Two different
if( condition ) { statements1; } else { statements2; }
SLIDE 8
if( condition1 ){ statement1;
if( condition2 ) {
if( condition3 ) statement2; …
}
}
SLIDE 9
Sometimes you probably break the speed
limit
But, there's one speed limit you can never
break
The speed of light c is about 3 x 108 m/s Given a variable named speed of type
double, what's an if-statement that will print an error message if speed is larger than c?
SLIDE 10 Recall the 4 quadrants of the Cartesian coordinate system Let's update our code to say if the point falls on the x axis, the
y axis, or the origin
x
y
(0,0) 1
2 3 4
SLIDE 11
SLIDE 12
Now you are controlling the flow of execution in your program There is a wider range of mistakes you can make when giving
instructions
Huge chunks of code can be executed or skipped by mistake Here are a few things to watch out for
SLIDE 13
Remember that an if-statement is not an executable
statement
It does not end with a semicolon
if( balance < 0 ); // empty statement { // this block always runs System.out.println("You owe a fee!"); balance -= 15; }
SLIDE 14
In some languages, indentation actually matters Java ignores whitespace "Fight!" prints no matter what
if( enemies > 2 ) System.out.println("Run away!"); else defense = true; System.out.println("Fight!");
SLIDE 15
It’s easy to make logical errors when writing conditions If an airline allows two or fewer bags on the plane, someone
might code that as:
But this is too restrictive. It should be:
if( bags < 2 ) { // only allows 1 or 0 boarding = true; } if( bags <= 2 ) { boarding = true; }
SLIDE 16
Sometimes it's easy to get a condition backwards Try not to assume you wrote the condition correctly Always double check
if( number % 3 == 0 ) { System.out.println("Not divisible by 3!"); } else { System.out.println("Divisible by 3!"); }
SLIDE 17
SLIDE 18
Finish switch statements More examples
SLIDE 19 Keep reading Chapter 4 of the textbook Start working on Project 2 Exam 1 next Monday