week 4: conditional execution 1. so far we have only considered java programs that do one thing...
Post on 19-Dec-2015
216 views
TRANSCRIPT
![Page 1: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/1.jpg)
1
CS 177Week 4: Conditional Execution
![Page 2: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/2.jpg)
2
Conditional execution
So far we have only considered Java programs that do one thing after another, in sequence
Our programs have not had the ability to choose between different possibilities
Now, they will!
![Page 3: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/3.jpg)
3
The if-statement
The if-statement:
“x is small” will only print if x is less than 5
In this case, we know that it is, but x could come from user input or a file or elsewhere
int x = 4;
if( x < 5 )System.out.println(“x is small!”);
![Page 4: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/4.jpg)
4
The if part
Any boolean expression
Any single executable statement
Anatomy of an if
if( condition ) statement;
![Page 5: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/5.jpg)
5
Conditions in the if
Any expression that evaluates to a boolean is legal in an if-statement
Examples: x == y mass > 21.75 Character.isDigit(gender) s.equals(“help”) && (z < 4)
![Page 6: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/6.jpg)
6
Comparison
The most common condition you will find is a comparison between two things
In Java, that comparison can be: == equals != does not equal < less than <= less than or equal to > greater than >= greater than or equal to
![Page 7: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/7.jpg)
7
Equals
You can use the == operator to compare any two things of the same type
Different numerical types can be compared as well (3 == 3.0)
Be careful with double types, 0.33333333 is not equal to 0.33333332
int x = 3;if( x == 4 )System.out.println(“This doesn’t print”);
![Page 8: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/8.jpg)
8
Not Equals
Any place you could have used the == operator, you can use the != operator
If == gives true, the != operator will always give false, and vice versa
If you want to negate a condition, you can always use the ! as a not
is the same as
if( x != 4 )
if( !(x == 4) )
![Page 9: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/9.jpg)
9
= != ==
Remember, a single equal sign (=) is the assignment operator (think of a left-pointing arrow)
A double equals (==) is a comparison operator
if( y = 6 ) //compiler error!
if( y == 6 ) //how to test if y is 6!
![Page 10: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/10.jpg)
10
Less Than (or Equal To)
Inequality is very important in programming
You may want to take an action as long as a value is below a certain threshold
For example, you might want to keep bidding at an auction until the price is greater than what you can affordif( x <= 4 )
if( x < 4 ) // what is the difference?
![Page 11: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/11.jpg)
11
Greater Than (or Equal To)
Just like less than or equal to, except the opposite
Note that the opposite of <= is > and the opposite of >= is <
Thus, !( x <= y ) is equivalent to ( x > y ) !( x >= y ) is equivalent to ( x < y )
![Page 12: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/12.jpg)
12
Either/Or
Sometimes you have to make a decision
If a condition is true, you go one way, if not, you go the other
For example: If I pass CS177,▪ Then I throw a party to celebrate
Otherwise,▪ I take it again and go to class next time
![Page 13: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/13.jpg)
13
Exclusivity
Notice the nature of this kind of condition
Both outcomes cannot happen Either a party gets thrown or you
take CS 177 again For these situations, we use the else
construct
![Page 14: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/14.jpg)
14
Anatomy of an if-else
Two different
outcomes
if( condition ) statement1;
elsestatement2;
![Page 15: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/15.jpg)
15
else example
double balance = …;
if( balance < 0 )System.out.println(“You are in debt!”);
elseSystem.out.println(“You have $” + balance);
![Page 16: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/16.jpg)
16
What if you need to do several things conditionally?
No problem Use braces to treat a group of
statements like a single statement
if( x == 4 ){System.out.println(“I hate 4”);System.out.println(“Let’s change x.”);x = 10;
}
![Page 17: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/17.jpg)
17
An if with multiple statements
if( condition ){
statement1;statement2;…statementn;
}
A whole bunch of
statements
![Page 18: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/18.jpg)
18
Nesting
Sometimes you want to make one set of decisions based on another set of decisions
if-statements can be nested inside the bodies of other if-statements
You can put if-statements inside of if-statements inside of if-statements… going arbitrarily deep
![Page 19: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/19.jpg)
19
Nested ifs
if( condition1 ){
statement1;if( condition2 ) {
if( condition3 )statement2;
…}
}
![Page 20: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/20.jpg)
20
An example using quadrants
For the next example, recall the 4 quadrants of the Cartesian coordinate system
x-x
y
-y
(0,0)
12
3 4
![Page 21: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/21.jpg)
21
Nesting example
Find which quadrant the point (x,y) is inif( x >= 0.0 )
{if( y >= 0.0 )
System.out.println(“Quadrant 1”);else
System.out.println(“Quadrant 4”);}else{if( y >= 0.0 )
System.out.println(“Quadrant 2”);else
System.out.println(“Quadrant 3”);}
![Page 22: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/22.jpg)
22
if and else if
You can list a sequence of exclusive possibilities using nesting:
if( index == 1 )System.out.println(“First”);
else if( index == 2 )System.out.println(“Second”);
else if( index == 3 )System.out.println(“Third”);
elseSystem.out.println(“Oops. Problem”);
}
![Page 23: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/23.jpg)
23
Watch out!
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…
![Page 24: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/24.jpg)
24
Empty statements
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 runsSystem.out.println(“You owe a fee!”);balance -= 15;
}
![Page 25: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/25.jpg)
25
Confusing indentation
In some languages, indentation actually matters
Java ignores whitespace
“Negotiate!” prints no matter what
if( enemies > 2 ) System.out.println(“Run away!”);
elsedefense = true;System.out.println(“Negotiate!”);
![Page 26: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/26.jpg)
26
Imprecise conditions
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 0boarding = true;
if( bags <= 2 )boarding = true;
![Page 27: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/27.jpg)
27
Reversed conditions
Sometimes it’s easy to get a condition backwards
Try not to assume you wrote the condition correctly
Always test your code
if( number % 3 == 0 ) System.out.println(“Not divisible by 3!”);
elseSystem.out.println(“Divisible by 3!”);
![Page 28: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/28.jpg)
28
Speed limit
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 miles/second
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?
![Page 29: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/29.jpg)
29
Speed limit answer
The simplest answer:
What if we want to add a message if the speed is legal?
if( speed > 3.0e8 )System.out.println(“Not so fast!”);
if( speed > 3.0e8 )System.out.println(“Not so fast!”);
elseSystem.out.println(“That speed is fine.”);
![Page 30: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/30.jpg)
30
DNA
Assume that you have a variable called base of type char
Let base contain one of: ‘A’, ‘C’, ‘G’, ‘T’ Write a series of if- and else-statements
that will print out the chemical name of the base denoted by the corresponding character A -> Adenine C -> Cytosine G -> Guanine T -> Thymine
![Page 31: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/31.jpg)
31
Printing DNA bases
What if you want to take care of upper and lower cases?
if( base == ‘A’ )System.out.println(“Adenine”);
else if( base == ‘C’ )System.out.println(“Cytosine”);
else if( base == ‘G’ )System.out.println(“Guanine”);
else if( base == ‘T’ )System.out.println(“Thymine”);
elseSystem.out.println(“Base is not correct”);
![Page 32: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/32.jpg)
32
Upper and lower case bases using logic
Is there a simpler way?
if( base == ‘A’ || base == ‘a’ )System.out.println(“Adenine”);
else if( base == ‘C’ || base == ‘c’ )System.out.println(“Cytosine”);
else if( base == ‘G’ || base == ‘g’ )System.out.println(“Guanine”);
else if( base == ‘T’ || base == ‘t’ )System.out.println(“Thymine”);
elseSystem.out.println(“Base is not correct”);
![Page 33: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/33.jpg)
33
Upper and lower case bases using character conversion
base = Character.toUpperCase( base );
if( base == ‘A’ )System.out.println(“Adenine”);
else if( base == ‘C’ )System.out.println(“Cytosine”);
else if( base == ‘G’ )System.out.println(“Guanine”);
else if( base == ‘T’ )System.out.println(“Thymine”);
elseSystem.out.println(“Base is not correct”);
![Page 34: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/34.jpg)
34
if statements are okay…
But, didn’t that DNA example seem a little clunky?
Surely, there is a cleaner way to express a list of possibilities
Yes! It is the switch statement
![Page 35: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/35.jpg)
35
Anatomy of a switch statement
switch( data ){
case value1:statements 1;
case value2:statements 2;
…case valuen:
statements n;default:
default statements;}
![Page 36: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/36.jpg)
36
DNA hittin’ switches
switch( base ){
case‘A’: System.out.println(“Adenine”);break;
case‘C’: System.out.println(“Cytosine”);break;
case‘G’: System.out.println(“Guanine”);break;
case‘T’: System.out.println(“Thymine”);break;
default: System.out.println(“Base is not correct”);break; // unnecessary
}
![Page 37: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/37.jpg)
37
Peculiarities of switch
int data = 3;switch( data ){
case 3:System.out.println(“Three”);
case 4:System.out.println(“Four”);break;
case 5:System.out.println(“Five”);
}
Both “Three” and “Four” are
printed
The break is optional
The default is
optional too
![Page 38: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/38.jpg)
38
Rules for switch
1. The data that you are performing your switch on must be either an int or a char
2. The value for each case must be a literal3. Execution will proceed to the case that
matches4. Execution will continue until it hits a break5. If no case matches, it will go to default6. If there is no default, it will skip the whole
switch block
![Page 39: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/39.jpg)
39
DNA with upper and lower case
switch( base ){ case‘A’: case‘a’:
System.out.println(“Adenine”);break;
case‘C’: case‘c’:
System.out.println(“Cytosine”);break;
case‘G’: case‘g’:
System.out.println(“Guanine”);break;
case‘T’: case‘t’:
System.out.println(“Thymine”);break;
default: System.out.println(“Base is not correct”);break; // unnecessary
}
![Page 40: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/40.jpg)
40
A caution about switch
Using if-statements is usually saferif-statements are generally clearer
and more flexibleswitch statements are only for long
lists of specific cases Be careful about inconsistent use of break
![Page 41: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/41.jpg)
41
Input
Input can be a messy thing So far, the only input you have used
are the arguments passed into the program
Sometimes a program needs to get input several times from a user
![Page 42: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/42.jpg)
42
StdIn
To do this, we are going to use the StdIn library, created by the author of the textbook
Read pages 126 – 130 in Sedgewick Java provides several other ways of
doing input However, StdIn is simpler than most The only painful thing is that you
have to have another class file in the directory with your program to make it work
![Page 43: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/43.jpg)
43
Downloading StdIn
The location of the StdIn library is: http://www.cs.princeton.edu/introcs/15inout/StdIn.java
This is just a regular Java file Look through it if you are curious When you compile code that uses StdIn methods, StdIn.java will automatically be compiled, as long as it is in the same directory
![Page 44: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/44.jpg)
44
Purpose of StdIn
The purpose of StdIn is to let you read stuff that the user types in
If the user is running the program from the command line, he or she will enter input there
If the user is running the program from DrJava, he or she will enter input in the Interactions pane
![Page 45: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/45.jpg)
45
DrJava vs. Command Line
DrJava
Command Line
![Page 46: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/46.jpg)
46
StdIn methods
For now, we are only going to focus on a few methods in StdIn
Method Use
int readInt() Read in the next int
double readDouble() Read in the next double
boolean readBoolean() Read in the next boolean
char readChar() Read in the next char
String readString() Read in the next String
String readLine() Read in a whole line
String readAll() Read in all remaining input
![Page 47: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/47.jpg)
47
Now we can make decisions before we read in more data
System.out.println(“How many sides does your shape have?”);int sides = StdIn.readInt();if( sides == 3 ){
System.out.println(“Enter the base and the height:”);double base = StdIn.readDouble();double height = StdIn.readDouble();System.out.println(“The area of your triangle is “ + (.5 * base * height ));
}else if( sides == 4 ){
System.out.println(“Enter the length and the width:”);double length = StdIn.readDouble();double width = StdIn.readDouble();System.out.println(“The area of your rectangle is “ + (length * width));
}else
System.out.println(“I don’t know what the area “ + “of your shape is.”);
![Page 48: Week 4: Conditional Execution 1. So far we have only considered Java programs that do one thing after another, in sequence Our programs have not had](https://reader030.vdocuments.site/reader030/viewer/2022032800/56649d2e5503460f94a05011/html5/thumbnails/48.jpg)
48
A few notes about StdIn
StdIn is pretty smart It can ignore whitespace when
looking for the next int or double It is not foolproof If you try to read in an int and the
user types “pigs”, your program will crash