Presentation is loading. Please wait.

Presentation is loading. Please wait.

Decisions, Decisions, Decisions

Similar presentations


Presentation on theme: "Decisions, Decisions, Decisions"— Presentation transcript:

1 Decisions, Decisions, Decisions
Conditional Statements In Java

2 Conditional Statements in Java
How would you explain to the Java compiler how to do the absolute value function? Seems simple enough in math All programming languages have some form of decision structure based on logic. The absolute value logic is: If the value is negative, multiply it by -1 In Java it would be written as: if( value < 0 ) { value = -1 * value; }

3 The if statement The syntax for an if statement in Java is:
if( condition ) { programming statements… } If the condition is true, java begins executing the code in the {}. Otherwise, the code in the {} is skipped Note the style!!! Indent Braces line up

4 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

5 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 }

6 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)

7 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. Adult: age >= 18 Child: not an adult We can write this as the following sentence: 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

8 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 );

9 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

10 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)

11 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”

12 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” ); } Can you spot the error? You can omit the block statements if you wish, but it is likely to result in more errors

13 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

14 Fixing Errors

15 Tracing by hand

16 Tracing by hand

17 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

18 A Whole Bunch of if’s False False False True True
if( richterScale < 1 ) { System.out.println( “Didn’t even feel it” ); } if( richterScale < 4 ) System.out.println( “All my dishes broke :(” ); if( richterScale < 7 ) System.out.println( “Whole lotta shakin going on!” ); if( richterScale < 10 ) 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! False True False True

19 Fixing the previous example
False if( richterScale < 1 ) { System.out.println( “Didn’t even feel it” ); } else if( richterScale < 4 ) System.out.println( “All my dishes broke :(” ); else if( richterScale < 7 ) System.out.println( “Whole lotta shakin going on!” ); else 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! False True, ignore anything else in the group False No if’s were true, so automatically go here

20 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

21 Complexity

22 if...else if…else syntax if( condition ) { statements if true }
else if( condition ) else statements if all others in the group were false

23 Class programming Challenge
Write a program that will calculate the cost for a patron to buy a movie ticket based on the following information: *be carful about your boundary cases Ex. What’s your age: 17 Your ticket costs $6.25 Under 13 13-19 20-64 65+ Cost $5.50 $6.25 $8.50

24 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 ); }

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”; 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 ); }

26 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

27 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:    Output (JString): Output (JString): You clicked on the circle You clicked on the oval Mouse Click

28 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

29 Lexicographical Order
Really means, “alphabetical order”, only our alphabet is much larger For Strings, the order of each character is:

30 Comparing Strings Strings are compared index by index until one of the characters is found to be different “testing” vs. “testinG” The first letters that do not match are g and G G comes before g so “testinG” would come first If two strings match for some portion, “Canucks” vs. “Canuck” 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 N G First character that does not match: N comes before S, so COMPARING is would come first

31 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

32 Which Comes First? “3456” or “56” “abc” or “123” “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! “abc” or “123” 1 comes before a, therefore, 123 is less than abc “Cat” or “Cat woman” 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

33 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

34 compareTo “abc”.compareTo(“def”); “def”.compareTo(“abc”);
Returns a negative to indicate that “abc” is less than “def” “def”.compareTo(“abc”); Returns a positive to indicate that “def” is larger than “abc” “abc”.compareTo(“abc”); 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

35 compareTo Consider two Strings:
String one = new String( “one” ); String two = new String( “two” ); if( one < two ) compares the ADDRESSES where the variables are stored (not useful in practice except when using equality) Instead you have to say: if( one.compareTo( two ) < 0 )// one < two There is also an equals method to compare two strings

36 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

37 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

38 Intro to Logic Logical statements evaluate to one of two things:
True False The three basic logical operators are: OR AND NOT Another common logical operator for programmer is the exclusive or, usually abbreviated to be XOR

39 Observations about and/or
In logic, ‘and’ is true when ALL variables are true ‘or’ is true when at least ONE variable is true In Java, 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 |

40 A little bit on logic A B A and B A or B T T T T F F F T F F

41 Your Turn Will the following statements be true or false?
(Horses have tails) OR (Fish have fur) (Dogs can fly) OR (Birds can fly) (Fish can swim) OR (Cats meow) (Pigs can fly) OR (horses can fly) T OR F = T F OR T = T T OR T = T F OR F = F

42 Your Turn Will the following statements be true or false?
(Horses have tails) AND (Fish have fur) (Dogs can fly) AND (Birds can fly) (Fish can swim) AND (Cats meow) (Pigs can fly) AND (horses can fly) T AND F = F F AND T = F T AND T = T F AND F = F

43 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

44 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.

45 Exercises (Cats fly) AND (Dogs bark) OR (Fish walk) F AND T OR

46 Exercises cont’ NOT (Pigs fly) AND (Birds fly) OR (Cats have gills)
(Fish walk) (T) AND (Birds fly) OR (Fish walk) (T) AND (T) OR (Fish walk) T OR (Fish walk) T OR F T

47 Exercises cont’ (Pigs fly) OR NOT (Birds fly) AND (Cats have gills)

48 Logical Operators Summary
Meaning && AND || OR ! Not

49 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

50 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 )

51 DeMorgan’s Law !(A && B) = !A || !B Similarly, !(A || B) = !A && !B

52 DeMorgan’s Law Speaking of simplicity…
Here is someone that is not a teenager: if(! (( age >= 13 ) && ( age < 20)) ) Note the extra parenthesis required since NOT would be done first! if( !(age >= 13 ) || !(age < 20) ) if( age < 13 || age >= 20 ) 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!

53 Short Circuit Evaluation
Let’s look at the truth tables for AND and OR: X Y X AND Y T F X Y X OR Y 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

54 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

55 Short Circuit Evaluation
This is a useful programming feature to prevent errors from happening: Ex. if(100 / number < 10) { programming statements… } As good programmers we should check that we’re not going to divide by 0 if( (number != 0) && (100 / number < 10)) 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

56 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

57 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.

58 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.


Download ppt "Decisions, Decisions, Decisions"

Similar presentations


Ads by Google