Week 4 - Monday
What did we talk about last time? if statements else statements Nested selection statements
The if part Any boolean expression if( condition ){ statements; } Executable statements
if( condition ) { statements1; } else { statements2; } Two different outcomes
if( condition1 ){ statement1; if( condition2 ) { if( condition3 ) statement2; … } }
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 10 8 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 ?
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 y 2 (0,0) 1 -x x 3 4 -y
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
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; }
In some languages, indentation actually matters Java ignores whitespace if( enemies > 2 ) System.out.println("Run away!"); else defense = true; System.out.println("Fight!"); "Fight!" prints no matter what
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: if( bags < 2 ) { // only allows 1 or 0 boarding = true; } But this is too restrictive. It should be: if( bags <= 2 ) { boarding = true; }
Sometimes it's easy to get a condition backwards Try not to assume you wrote the condition correctly if( number % 3 == 0 ) { System.out.println("Not divisible by 3!"); } else { System.out.println("Divisible by 3!"); } Always double check
Finish switch statements More examples
Keep reading Chapter 4 of the textbook Start working on Project 2 Exam 1 next Monday Review on Friday
Recommend
More recommend