Here are my notes (exercises contained inside)
Download
Report
Transcript Here are my notes (exercises contained inside)
Decisions, Decisions, Decisions
Conditional
Statements
In Java
Conditional Statements in Java
How would you explain to the Java compiler how to
do the absolute value function?
All programming languages have some form of
decision structure based on logic.
The absolute value logic is:
Seems simple enough in math
If the value is negative, multiply it by -1
In Java it would be written as:
if( value < 0 )
{
value = -1 * value;
}
The if statement
The syntax for an if statement in Java is:
if( condition )
{
programming statements…
Indent
}
Braces line up
If the condition is true, java begins executing the code
in the {}. Otherwise, the code in the {} is skipped
Note the style!!!
Common Error #1
if (radius < 0) ;
{
System.out.print( “radius is negative, “ );
System.out.print( radius + “ is invalid” );
}
Java thinks you mean:
if (radius < 0) { }//empty statement because of the semi-colon
{
System.out.print( “radius is negative, “ );
System.out.print( radius + “ is invalid” );
}
Scope example
public static void main( String[] args )
{
Scanner in = new Scanner( System.in );
System.out.println( “Enter a hours worked: “ );
double hours = in.nextInt();
if( hours < 0 )
{
double wage = 15.75;
hours = -1 * hours;//make positive
System.out.println( “I think you meant: ” + hours );
}//wage live until here, the end of it’s block
System.out.println( “Your wage is: “ + hours * wage );//error, wage is out of scope
}
Conditional Operators
Symbol in Java
Meaning
==
Equals
!=
Not Equal
<
Less Than
<=
Less Than or Equal
>
Greater Than
>=
Greater Than or Equal
Common mistake is to use = (assignment) when you meant == (test if equal)
if … else statements
Another programming feature with decisions is the
if… else statement
Suppose you’re charging admission for a theatre and
the ticket prices are for children or adults.
We can write this as the following sentence:
Adult: age >= 18
Child: not an adult
If age is 18 or higher, charge adult price, otherwise charge
child price
The new keyword in our problem is otherwise which
translates in Java to else
if … else statements
In java the code for the movie theatre is:
final double ADULT_PRICE = 10.75;
final double CHILD_PRICE = 8.25;
int ticketPrice;
if( age >= 18 )//this person is an adult
{
ticketPrice = ADULT_PRICE;
}
else//this person is not an adult, therefore a child
{
ticketPrice = CHILD_PRICE;
}
System.out.println( “Your ticket price is: “ + ticketPrice );
if … else
The syntax for if … else in java is:
if( condition )
{
programming statements if true
}
else
{
programming statements if false
}
If the original condition is true, then the code in the
{} associated with the if statement is executed
Otherwise, the code is ignored and the code in the {}
associated with the else statement is executed
Example Program I
Write the following method to determine
someone’s paycheque:
If they work over 40 hours then pay them double the wage for each
hour over 40.
public static double payCheque(double wage, double hours)
Example Program II
Write the following method:
public static void printTime(int hours, int minutes)
printTime(5,15) “5:15am”
printTime(15,5) “3:05pm”
Block Statements
In our class I will always use block statements for conditions and loops.
A condition or loop with only one statement in the body does not require a block
statement:
Ex.
if( age > 16 )
{
System.out.println( “You may get your liscence” );
}
Ex.
if( age > 16 )
System.out.println( “You may get your liscence” );
Can you spot the error?
You can omit the block statements if you wish, but it is likely to result in more errors
Block Statements
Another advantage of block statements is clarity.
Which if does the else belong to?
If we add braces it is clearer which it belongs to
Fixing Errors
Tracing by hand
Tracing by hand
And finally, if…else if…else
What about when there are several conditions
that are related?
In order to ensure that only one statement is
executed, we need to chain the if’s together.
The next two slides show an example where
the limitations of only having if are illustrated
A Whole Bunch of if’s
if( richterScale < 1 )
{
System.out.println( “Didn’t even feel it” );
}
False
if( richterScale < 4 )
{
System.out.println( “All my dishes broke :(” );
}
False
True
False
if( richterScale < 7 )
{
System.out.println( “Whole lotta shakin going on!” );
}
if( richterScale < 10 )
{
System.out.println( “Run for the hills!” );
}
True
What does the code print if richterScale = 8?
Run for the hills!
What does the code print if richterScale = 5?
Whole lotta shakin going on!
Run for the hills!
Fixing the previous example
if( richterScale < 1 )
{
System.out.println( “Didn’t even feel it” );
}
else if( richterScale < 4 )
{
System.out.println( “All my dishes broke :(” );
}
False
False
True, ignore anything
the group
False
else if( richterScale < 7 )
else in
{
System.out.println( “Whole lotta shakin going on!” );
}
else
{
No if’s were true, so
automatically go here
System.out.println( “Run for the hills!” );
}
What does the code print if richterScale = 8?
Run for the hills!
What does the code print if richterScale = 5?
Whole lotta shakin going on!
if...else if…*else
Java evaluates EVERY if statement.
The only exception is when they are joined by
the reserved word else
Java evaluates a sequence of if/else if/else
statements until the FIRST one is true.
If none are true then the else is evaluated
Only one set of statements in the group will be
evaluated
*An else is not required
Complexity
if...else if…else syntax
if( condition )
{
statements if true
}
else if( condition )
{
statements if true
}
…
…
else if( condition )
{
statements if true
}
else
{
statements if all others in the group were false
}
Class programming Challenge
Write a program that will calculate the cost for
a patron to buy a movie ticket based on the
following information:
Cost
Under 13
13-19
20-64
65+
$5.50
$6.25
$8.50
$5.50
*be carful about your boundary cases
Ex. What’s your age: 17
Your ticket costs $6.25
Correctness
public static void main(String[] args)
{
Scanner in = new Scanner( System.in );
System.out.println( "Enter your number grade (integer from 0 to 100): “ );
int percent = in.nextInt();
String grade;
if (percent >= 86)
grade = “A”;
if (percent >= 73)
grade = “B”;
if (percent >= 67)
grade = “C+”;
if (percent >= 60)
grade = “C”;
if (percent >= 50)
grade = “C-”;
else
grade = “F”;
System.out.println( "The letter grade is: " + grade );
}
Correctness
public static void main(String[] args)
{
Scanner in = new Scanner( System.in );
System.out.println( "Enter your number grade (integer from 0 to 100): “ );
int percent = in.nextInt();
String grade;
if (percent >= 86)
grade = “A”;
else if (percent >= 73)
grade = “B”;
else if (percent >= 67)
grade = “C+”;
else if (percent >= 60)
grade = “C”;
else if (percent >= 50)
grade = “C-”;
else
grade = “F”;
System.out.println( "The letter grade is: " + grade );
}
Decisions Practice I
Write a program that asks the user to guess a random number between 1
and 10 and tell them if they guessed correctly.
Ex.
Guess a number between 1 and 10: 9
Sorry, the number was 6
Guess a number between 1 and 10: 2
That’s correct!
Write a program that creates a JShape (your choice) in a random location
on the screen (but don’t draw it yet). Ask the user to guess its location by
trying to click on it. After they click, draw the circle and check if they
managed to guess correctly (use the isInside method). Display a
congratulatory message if they guessed right, otherwise display a message
that mocks them
Decisions Practice I cont’
Create a simple child’s game to teach them about shapes. They will click
on a shape and you will tell them which one they chose. Your game must
have at least 4 shapes.
Mouse Click
Mouse Click
Run #1:
Run #2:
Mouse Click
Output (JString):
You clicked on the circle
Mouse Click
Output (JString):
You clicked on the oval
Primitive Types vs. Objects
You may have noticed so far that we’ve only been
comparing, int and double values.
In java, the comparison operators only work for
primitive types
Objects that can be compared will have methods
instead
For example, in the String class, all String objects
have the methods: compareTo and equals
All objects in Java that implement the Comparable
interface have the method compareTo
Lexicographical Order
Really means, “alphabetical
order”, only our alphabet is
much larger
For Strings, the order of each
character is:
Comparing Strings
Strings are compared index by index until one of the
characters is found to be different
“testing” vs. “testinG”
If two strings match for some portion,
“Canucks” vs. “Canuck”
The first letters that do not match are g and G
G comes before g so “testinG” would come first
The empty character always wins, “Canuck” would come first
It is usually a good idea to write strings on top of each other
when comparing: C O M P A R I S O N
C
O
M
P
A
R
I
First character that does not match:
N comes before S, so COMPARING is would come first
N
G
Lexicographical Rules
Java uses the Unicode character set for its
strings.
There are 65536, so a convenient summary is:
Numbers come before letters
Capitals before lower case
Lower case are after capitals
That’s enough for most applications done by
hand
Which Comes First?
“3456” or “56”
“abc” or “123”
First place they don’t match: index 0
1 comes before a, therefore, 123 is less than abc
“Cat” or “Cat woman”
First place they don’t match: index 0
3 comes before 5, therefore, 3456 is less than 56
Remember, this is String comparison not numbers!
First place they don’t match: index 3
“Cat woman” still has characters remaining, “Cat” is less than “Cat woman”
“aaAA” or “aA”
First place they don’t match: index 1
A comes before a, therefore, aA is less than aaAA
Comparing Strings
Java can determine lexicographic order by
using the compareTo method
The compareTo method is not unique to String
compareTo replaces all comparison operators
for Strings
compareTo
“abc”.compareTo(“def”);
“def”.compareTo(“abc”);
Returns a positive to indicate that “def” is larger than “abc”
“abc”.compareTo(“abc”);
Returns a negative to indicate that “abc” is less than “def”
Returns 0 to indicate that the strings are equal
compareTo returns 3 values:
An integer less than 0 to indicate the calling string is less
than the argument string
An integer greater than 0 to indicate the calling string is
greater than the argument string
0 to indicate the calling string is equal to the argument
string
compareTo
Consider two Strings:
if( one < two ) compares the ADDRESSES
where the variables are stored (not useful in
practice except when using equality)
Instead you have to say:
String one = new String( “one” );
String two = new String( “two” );
if( one.compareTo( two ) < 0 )// one < two
There is also an equals method to compare two
strings
compareTo
Primitive Types
Objects
one < two
one.compareTo( two ) < 0
one <= two
one.compareTo( two ) <= 0
one > two
one.compareTo( two ) > 0
one >= two
one.compareTo( two ) >= 0
one == two
one.compareTo( two ) == 0
one != two
one.compareTo( two ) != 0
Always being compared with 0
Operator stays the same
String Practice
A simple Pig Latin is one where words beginning in
consonants are moved to the end and ‘ay’ is appended
(consider ‘y’ a consonant). Implement the code to do this:
input School
output choolSay
input car
output arcay
input architect
output architectay
input yellow
output ellowyay
Write a program that asks for the name of a province or
territory in Canada. Tell the user the capital city (for example,
in British Columbia, the capital is Victoria). If the name is
invalid, tell them the province or territory was not recognized.
Write a program that takes a student’s last name and tells them
which counsellor and vice principal at our school is theirs
Intro to Logic
Logical statements evaluate to one of two
things:
The three basic logical operators are:
True
False
OR
AND
NOT
Another common logical operator for
programmer is the exclusive or, usually
abbreviated to be XOR
Observations about and/or
In logic,
In Java,
‘and’ is true when ALL variables are true
‘or’ is true when at least ONE variable is true
AND is represented by &&
OR is represented by ||
NOT is represented by !
IMPORTANT!
& and | mean something else in Java (binary logic operators), your program
will compile fine, but produce unexpected results
Make sure you use && and ||, we will not be using & or |
A little bit on logic
AB
A and B
A or B
TT
T
T
TF
F
T
FT
F
T
FF
F
F
Your Turn
Will the following statements be true or false?
(Horses have tails) OR (Fish have fur)
T
OR
F
=
(Dogs can fly) OR (Birds can fly)
F
OR
T
= T
(Fish can swim) OR (Cats meow)
T
OR
T
=
(Pigs can fly) OR (horses can fly)
F
OR
F
=
T
F
T
Your Turn
Will the following statements be true or false?
(Horses have tails) AND (Fish have fur)
T
AND
F
=
(Dogs can fly) AND (Birds can fly)
F
AND
T
= F
(Fish can swim) AND (Cats meow)
T
AND
T
= T
(Pigs can fly) AND (horses can fly)
F
AND
F
= F
F
Not!
In logic, when we say a statement is negated or
we take its negation, what we really mean is
‘not’.
Not makes a true expression false
Not makes a false expression true
Precedence
Like Mathematics, logic has an order of
operations
Not has the highest (done first)
Followed by AND
Followed by OR
Brackets work the same way you already know
in changing the order of operations.
Exercises
(Cats fly) AND (Dogs bark) OR (Fish walk)
F
AND T
OR (Fish walk)
F
OR
(Fish walk)
F
OR
F
F
Exercises cont’
NOT (Pigs fly) AND (Birds fly) OR (Cats have gills)
NOT
(F) AND (Birds fly) OR (Fish walk)
(T) AND (Birds fly) OR (Fish walk)
(T)
AND
(T)
OR (Fish walk)
T
OR
(Fish walk)
T
OR
F
T
Exercises cont’
(Pigs fly) OR NOT (Birds fly) AND (Cats have gills)
(Pigs fly) OR NOT
(Pigs fly)
(Pigs fly)
OR
(T)
AND (Cats have gills)
(F)
AND (Cats have gills)
(F)
AND
OR
(Pigs fly)
F
OR
OR
F
F
F
(F)
Logical Operators Summary
Operator
Meaning
&&
AND
||
OR
!
Not
Using compound statements
It is often the case that a single condition is not
enough to satisfy our constraints
A compound logic statement is one that uses the &&
or || operators (or some combination)
For example, we can represent a teenager as:
if( (age >=13) && (age < 20) )
In math when a value is between 13 and 19, we write:
13 <= x < 20
It can be written in Java as (13 <= x && x < 20) to resemble math
Boolean Variables
Sometimes a statement can be very cluttered by logical
operators
One way to improve the readability of your code is to store the
T/F result in a boolean
Suppose you are looking to find adults and children. These
people are not teenagers and not senior citizens.
Option #1:
if( !(13 <= age && age < 20) && ! age >= 65)
Option #2
boolean teenager = 13 <= age && age < 20;
boolean senior = age >= 65;
if( !teenager && !senior )
DeMorgan’s Law
!(A && B) = !A || !B
Similarly,
!(A || B) = !A && !B
DeMorgan’s Law
Speaking of simplicity…
Here is someone that is not a teenager:
if(! (( age >= 13 ) && ( age < 20)) )
if( !(age >= 13 ) || !(age < 20) )
if( age < 13 || age >= 20 )
Note the extra parenthesis required since NOT would be done first!
A teenage is also someone who is less than 13 or at least 20
In general, it is always best to use the simplest statement!
Short Circuit Evaluation
Let’s look at the truth tables for AND and OR:
X
T
T
F
F
Y
T
F
T
F
X AND Y
T
F
F
F
X
T
T
F
F
Y
T
F
T
F
X OR Y
T
T
T
F
Notice that when one value is true, it does not matter what the
others are, OR will be true
Notice that when one value is false, it does not matter what
the others are, AND will be false
Java is Lazy?
Java uses short circuit evaluation to evaluate
conditions.
This means that:
if( TRUE || (other conditions) )
Java ignores everything after the || since the result
will be true no matter what else is combined
if( FALSE && (other conditions) )
Java ignores everything after the && since the
result will be false no matter what else is combined
Short Circuit Evaluation
This is a useful programming feature to prevent errors from
happening:
Ex.
As good programmers we should check that we’re not going to
divide by 0
if(100 / number < 10)
{
programming statements…
}
if( (number != 0) && (100 / number < 10))
{
programming statements…
}
Due to short circuit evaluation, the division will not happen if number == 0
since that makes the statement number != 0 false and the rest is ignored
Nesting statements
Nesting conditions can make it easier to follow than
using many && or || operators
Here is the condition of a teenage boy
if(gender.equals(“male”) && (13 <= age) && (age <= 19))
{
programming statements…
}
Is equivalent to:
if(gender.equals(“male”))//must be male to make it in {}
{
if(13 <= age) && (age <= 19))//teenager
{
programming statements…
}
}
Decisions Practice II
Leap years: A leap year is any year which
Is divisible by 4 and not divisible by 100
Years divisible by 400 are leap years.
The Gregorian Calendar was introduced in 1582 so
leap years can be calculated from this point on.
For example 1900 is not a leap year, but 2000 is.
Write a program that tells the user whether the
year they enter is a leap year or not.
Rock Paper Scissors
Create a rock paper scissors game in JGraphics
Each of the items can be simulated by a random number.
Ex.
final int ROCK = 0;
final int PAPER = 1;
final int SCISSORS = 2;
final int ITEMS = 3;//3 items in this game
int computerChoice = (int)(Math.random()*ITEMS);//0-2
Now computerChoice can act as if the computer chose rock, paper or
scissors.
The user can make their selection by clicking with the mouse on the object
they want… anyone want to play rock, paper, scissors, lizard, spock (big
bang theory – see youtube)?
Determine who wins the game and display the result to the user.