Presentation is loading. Please wait.

Presentation is loading. Please wait.

The “if” Control Sections 3.1 & 3.2

Similar presentations


Presentation on theme: "The “if” Control Sections 3.1 & 3.2"— Presentation transcript:

1 The “if” Control Sections 3.1 & 3.2
Making Choices The “if” Control Sections 3.1 & 3.2

2 Overview Having the program choose an action The boolean data type
the if control comparing Strings the else control nesting controls The boolean data type our own boolean methods combining boolean conditions

3 Making a Choice Calculating an employee’s pay get their hourly pay
get how many hours they worked calculate their standard pay if they worked more than 40 hours: add overtime pay issue a cheque for the total pay Sometimes overtime pay is added; sometimes it’s not. Depends on how many hours they worked.

4 Conditional Commands “Add overtime pay” is conditional
computer doesn’t always do that “worked more than 40 hours” is the condition if it’s true, then computer adds overtime pay In English/pseudocode: “if they worked more than 40 hours, then add overtime pay” How to write that in Java?

5 The “if” Control Java syntax: if (condition) { conditionalAction; }
note braces go around the command you maybe want to do note indentation: conditional action indented another four spaces! also note: no semi-colon on the “if” line “if they worked over 40 hours” is not a command if (over40Hours) { pay = pay + … } Remember the Format command in NetBeans! It will do the indentation for you.

6 “if” Control Example System.out.print("Hours this week: "); hours = kbd.nextDouble(); kbd.nextLine(); pay = rate * hours; if (hours > 40) { System.out.println("You get overtime pay."); pay = pay + rate * 1.5 * (hours – 40); } Condition Conditional Actions Hours this week: 30 Hours this week: 45 You get overtime pay. no overtime pay overtime pay

7 Simple Comparisons if (hours > 40)  “if hours is greater than 40ˮ
Can also put “ifˮ in front of these: a == b “a is equal to bˮ a != b “a is not equal to bˮ a < b “a is less than bˮ a <= b “a is less than or equal to bˮ a > b “a is greater than bˮ a >= b “a is greater than or equal to bˮ You can’t use the ≤ or ≥ signs in Java. It doesn’t understand them!

8 Important Difference Check whether a is equal to b: a == b
two equals signs Make a equal to b: a = b one equals sign Do not get them confused hours == kbd.nextDouble(); if (hours = 40.0) { not a statement ! incompatible types: double cannot be converted to boolean !

9 Exercises Write if statements:
if grade is greater than or equal to 50, print out “You passed!” if age is less than 18, print out “I’m sorry, but you’re not allowed to see this movie.” if guess is equal to secretNumber, print out “You guessed it!” if y plus 9 is less than or equal to x times 2, set z equal to zero.

10 Sequential “if” Controls
Each “if” is separate if (grade < 50) { System.out.println("I’m sorry. You failed."); } if (grade > 90) { System.out.println("That is an excellent grade!"); What grade did you get? 41 I’m sorry. You failed. What grade did you get? 95 That is an excellent grade! one other What grade did you get? 75 neither

11 Sequential “if” Controls
Each “if” is separate if (grade >= 50) { System.out.println("You passed."); } if (grade < 80) { System.out.println("You didn’t get an A."); What grade did you get? 41 You didn’t get an A+. What grade did you get? 95 You passed. one other What grade did you get? 75 You passed. You didn’t get an A. both

12 Sequential “if” Controls
Each “if” is separate if (midtermGrade < 50) { System.out.println("You failed the midterm! "); } if (finalGrade < 50) { System.out.println("You failed the final! "); You failed the midterm! You failed the final! both You failed the midterm! You failed the final! one other neither

13 Exercise What is the output of the following code? int age = 24;
int height = 180; int weight = 70; int income = ; if (age < 18) { System.out.println("Young!"); } if (height > 180) { System.out.println("Tall!"); } if (weight <= 50) { System.out.println("Thin!"); } if (income >= ) { System.out.println("Rich!"); }

14 Making a Choice Taking a lunch order at Greesieberger’s
ask what sandwich they want add that sandwich to the order ask if they want fries with that if they say yes: add fries to the order ask what drink they want add that drink to the order Sometimes fries are added to the order; sometimes they’re not. Depends on what the user wants.

15 Choosing Fries Ask the user: Do you want fries with that?
Get user’s answer (should be yes or no) if the answer was yes, add fries to the order In Java (but not right) System.out.print("Do you want fries? "); String answer = kbd.next(); kbd.nextLine(); if (answer == "yes") Comparing Strings using == or != !

16 Object Variables Strings are objects
== means “Are they the very same object?” as in “My car and my wife’s car are the same car” want “Are they the same value?” as in “I have the same car as my neighbour” My Car My Wife’s Car My Neighbour’s Car The String in the code What the user typed in "yes" "yes"

17 Comparing Strings How to ask about Strings
don’t use ==, !=, <, <=, >, >= they don’t work (or they do the wrong thing) ==  oneString.equals(anotherString) !=  ! oneString.equals(anotherString) <  oneString.compareTo(anotherString) < 0 <=  oneString.compareTo(anotherString) <= 0 >  oneString.compareTo(anotherString) > 0 >=  oneString.compareTo(anotherString) >= 0 We won’t use compareTo very often.

18 String Equality Strings are equal if exactly the same
"First String".equals("First String") Any other strings are different! ! "First String".equals("Second String") ! "First String".equals("first string") ! "First String".equals("FirstString") ! "First String".equals("First String ") NOT equals

19 Choosing Fries In Java System.out.println("Do you want fries?");
String answer = kbd.next(); kbd.nextLine(); if (answer.equals("yes")) only accepts “yes” does not accept “Yes”, “YES”, …

20 String.equalsIgnoreCase
Sometimes don’t care if capital or small "First String".equalsIgnoreCase("First String") "First String".equalsIgnoreCase("first string") Any other strings are different! ! "First String".equalsIgnoreCase("Second String") ! "First String".equalsIgnoreCase("FirstString") ! "First String".equalsIgnoreCase("First String ") NOT equals (ignoring case)

21 Choosing Fries In Java System.out.println("Do you want fries?");
String answer = kbd.next(); kbd.nextLine(); if (answer.equalsIgnoreCase("yes")) accepts “yes”, “Yes”, “YES”, … (does not accept “yeah”)

22 String.startsWith Accept any answer starting with “y” as yes
System.out.println("Do you want fries?"); String answer = kbd.next(); kbd.nextLine(); if (answer.startsWith("y")) Accepts “yes”, “yeah”, “yup”, but not “Yes” sadly, there is no “startsWithIgnoreCase” method There’s also an endsWith method. And lots of others! Google java string.

23 String.toUpperCase/toLowerCase
Ask a string for upper/lower case version System.out.println("Do you want fries?"); String answer = kbd.next(); kbd.nextLine(); String upperAnswer = answer.toUpperCase(); if (upperAnswer.startsWith("Y")) now accepts “Yes”, “yes”, “Yeah, “yup”, … upperAnswer is “YES”, “YES”, “YEAH”, “YUP” answer is still “Yes”, “yes”, “Yeah”, “yup”

24 String.oneThing().another()
Can combine two steps into one and more, if you want System.out.println("Do you want fries?"); String answer = kbd.next(); kbd.nextLine(); if (answer.toUpperCase().startsWith("Y")) if answer is “yes”, then answer.toUpperCase() is “YES”, and that does start with a “Y”

25 Scanner.oneThing().another()
Can save the String in upper case to start with and more, if you want System.out.println("Do you want fries?"); String answer = kbd.next().toUpperCase(); kbd.nextLine(); if (answer.startsWith("Y")) change user’s answer to upper case before saving it user enters “yes”; answer is “YES” user enters “Yup”; answer is “YUP”

26 Exercise Code above treats “sure” as “no”
it doesn’t start with “Y” or “y” Change the code so that it adds fries to anyone whose answer doesn’t start with N big N or little n both count as no if (answer.toUpperCase().startsWith("Y")) ???

27 The “if-else” Control Do exactly one of two things
if (grade < 50) { System.out.println("You cannot continue to "); } else { System.out.println("You can continue to 1227! "); } note the indentation What grade did you get? 41 You cannot continue to 1227. What grade did you get? 95 You can continue to 1227! one other

28 The “if-else” Control Java syntax:
if (condition) { ifSoAction; } else { otherwiseAction; } Does exactly one of those two things two-way choice do this or do that “if” is one-way choice do this or not

29 Better Than Two if Controls
Could rewrite if-else into two if controls: if (grade < 50) { System.out.println("You cannot continue to "); } if (grade >= 50) { System.out.println("You can continue to 1227! "); but that’s error-prone makes it more likely you’ll make a mistake

30 Error-Prone Version What’s wrong with this: if (grade < 50) {
System.out.println("You cannot continue to "); } if (grade > 50) { System.out.println("You can continue to 1227! ");

31 Error-Prone Version For 1228 you need a 60, so…
copy the code and make the required changes if (grade < 60) { System.out.println("You cannot continue to "); } if (grade >= 50) { System.out.println("You can continue to 1228! "); what went wrong?

32 Binary Choices Else is for either-or situations
either you pass or you fail no program option for incomplete either you can proceed or you cannot either go left or go right no program option for straight State the condition once Split options between if-body and else-body

33 Exercise Write if-else controls for
if temp is over 30, print “Go swimmingˮ; otherwise print “Play video gamesˮ if count is zero, print sum divided by count; otherwise print “No numbers enteredˮ. if answer starts with a y (or Y), then set price to $10; otherwise set it to $15. if num is even, set it equal to n divided by 2; otherwise set it to n times 3, plus 1 num is even  num % 2 == 0

34 Sometimes prints B and C;
“if” or “if-else”? Look at the possible outcomes: outcome #1 computer prints A B C D outcome #2 computer prints A D code: Sometimes prints B and C; Sometimes doesn’t: (if control) System.out.print("A "); if (something) { System.out.print("B "); System.out.print("C "); } System.out.print("D ");

35 “if” or “if-else”? Look at the possible outcomes: outcome #1
computer prints A B D outcome #2 computer prints A C D code: Sometimes prints B; Sometimes prints C: (if-else control) System.out.print("A "); if (something) { System.out.print("B "); } else { System.out.print("C "); } System.out.print("D ");

36 Exercise Possible outcomes: outcome #1: A, B, C, E, F
outcome #2: A, D, E, F What is the code? outcome #1: A, B, C, D outcome #2: A, B

37 Exercise Possible outcomes: outcome #1: A, B, C, F, G
outcome #2: A, D, E, F, G outcome #3: A, B, C, F outcome #4: A, D, E, F What is the code?

38 A Common Mistake Putting braces around everything after if
if (thisIsTrue) { doThis(); andThat(); else thisOther(); } the else must be after the closing brace of the if otherwise can’t find the if its the else for 'else' without 'if' !

39 if-else inside if-else
What time is it? 9 pm Good evening! What time is it? 9 am Good morning! M E Evening: 6pm to 11pm. Morning: 7am to 11am. What time is it? 3 pm Good afternoon! What time is it? 3 am Good grief! A G Afternoon: 12pm to 5pm. 12am to 6 am. pm am

40 Get the Time // create variables Scanner kbd = new Scanner(System.in);
int hour; String amPM; // get the time System.out.println("What time is it?"); hour = kbd.nextInt(); // fix weird clock if (hour == 12) { hour = 0; } // NOTE: read next word in lower case amPM = kbd.next().toLowerCase(); kbd.nextLine(); // read the Enter key!

41 Print the Message A E M G // print the appropriate message
if ( amPM.equals("pm") ) { if ( hour < 6 ) { System.out.println("Good afternoon!"); } else { System.out.println("Good evening!"); } if ( hour > 6 ) { System.out.println("Good morning!"); System.out.println("Good grief!"); A E M G

42 9 AM Message "am".equals("pm")? NO 9 > 6? YES
// print the appropriate message if ( amPM.equals("pm") ) { if ( hour < 6 ) { System.out.println("Good afternoon!"); } else { System.out.println("Good evening!"); } if ( hour > 6 ) { System.out.println("Good morning!"); System.out.println("Good grief!"); "am".equals("pm")? NO 9 > 6? YES

43 Note Indentation 8 12 16 Remember the Format command!
// print the appropriate message if ( amPM.equals("pm") ) { if ( hour < 6 ) { System.out.println("Good afternoon!"); } else { System.out.println("Good evening!"); } if ( hour > 6 ) { System.out.println("Good morning!"); System.out.println("Good grief!"); Remember the Format command!

44 if inside if You can put if controls inside if controls
if first condition is true, test second condition System.out.println("A"); if (condition1) { System.out.println("B"); if (condition2) { System.out.println("C"); } possible output: A AB ABC pattern: always A sometimes B when B, sometimes C

45 Eligible for Pension Who is eligible for a pension
seniors (age is 65+) disabled people 55+ who live on their own Only ask question if need to know ask age if 65+  eligible if 55+ and not already eligible ask if disabled if disabled ask if live on own if live on own  eligible

46 Eligible for Pension // ask age System.out.print("How old are you? "); age = kbd.nextInt(); kbd.nextLine(); eligible = (age >= 65); // if , ask if disabled if (age >= 55 && !eligible) { System.out.print("Are you disabled? "); answer = kbd.nextLine().toLowerCase(); // if disabled, ask if live on own if (answer.startsWith("y")) { System.out.print("Do you live on your own? "); eligible = answer.startsWith("y"); }

47 Exercise Write nested if/if-else to generate:
either "A", "AB", "ABC" or "ABD" either "A", "ABC" or "AC" either "A", "ABC", or "D"

48 Logical Operators p && q p and q both true
(0 < n) && (n < 100) p || q either p or q (or both) are true (m > 0) || (n > 0) !p p is not true !answer.equals("yes")

49 On Translating from English
In English we can leave things unsaid if x is greater than 0 and less than 100, ... In Java, we can’t if (x > 0 && < 100) computer: Huh?? Start by saying the whole thing in English if x is greater than 0 and x is less than 100, ... if (x > 0 && x < 100) computer: OK

50 Warnings Use the right operators Nothing goes without saying! == not =
a > 0 && a < 10 not a > 0 && < 10 b == 0 || c == 0 not b || c == 0 0 < d && d < 10 not 0 < d < 10

51 Exercises Write Boolean expressions for whether…
x is greater than 0 and y is less than 5 x is greater than zero or y is equal to z answer does not start with N it’s not the case that x is greater than the product of y and z NOTE: translate directly to Java y is greater than x and less than z x is equal to y but not to z m or n is greater than 0

52 Three-Way Choice Exactly one of three options either "A", "B", or "C"
if (age < 18) { System.out.print("Child"); } if (age >= 18 && age < 65) { System.out.print("Adult"); if (age >= 65) { System.out.print("Senior"); age is 15 Child age is 25 Adult age is 65 Senior

53 Sequential If and If-Else
Be careful mixing if with if-else else parts go with each if separately if (age < 18) { System.out.print("Child"); } if (age >= 18 && age < 65) { System.out.print("Adult"); } else { System.out.print("Senior"); What happens when age = 15? age is 25 Adult age is 65 Senior

54 If-Else Inside Else If-Else inside an Else
only do Adult/Senior choice if Child not chosen if (age < 18) { System.out.print("Child"); } else { if (age >= 18 && age < 65) { System.out.print("Adult"); System.out.print("Senior"); } What happens when age = 15? age is 25 Adult age is 65 Senior

55 If-Else Inside Else So common it has a special style
second if comes right after the else (no braces) if (age < 18) { System.out.print("Child"); } else if (age >= 18 && age < 65) { System.out.print("Adult"); } else { System.out.print("Senior"); } behaves exactly the same as previous slide

56 Cascading If Statements
Simplified conditions already know age >= 18 in part 2 if (age < 18) { System.out.print("Child"); } else if (age < 65) { System.out.print("Adult"); } else { System.out.print("Senior"); } What happens when age = 15? age is 25 Adult age is 65 Senior

57 Multi-Way Choice A or B or C or ... or Z
if (...) { doA(); } else if (...) { doB(); ... } else { doZ(); } A or B or ... or Z or none of the above if (...) { doA(); } else if (...) { doB(); ... doZ(); } If we didn’t do any of the others, then we’ll do Z for sure If we didn’t do any of the others, we still might not do Z

58 Exercises Write "Good morning" if time < 12, "Good afternoon" if 12  time < 17, "Good evening" otherwise Write "Small" if size is 1, "Medium" if size is 2, "Large" if size is 3, "X-Large" if size is 4, and "XX-Large" if size is 5 don’t write anything if size is not 1..5

59 Boolean Values Comparison operators evaluate to true or false
20 < 40 is true; 40 < 20 is false NOTE: true and "true" are entirely different just like 65.0 and "65.0" true and false are called “Booleanˮ values after George Boole, who studied logic 20 < 40 is called a “Boolean expressionˮ its value is a Boolean value &&, || and ! are called “Boolean operatorsˮ allow us to make bigger Boolean expressions

60 Boolean Variables Can save the answer to a comparison
use a boolean variable boolean workedOvertime = (hours > 40); you don’t need parentheses, but it’s easier to read Can use the saved result as a condition if (workedOvertime) { overtimeHours = hours – 40; regularPay = 40 * rate; overtimePay = overtimeHours * rate * 1.5; }

61 Boolean Variable Answer to a “True or False” question True or False?
The hours worked is over 40. workedOvertime = (hoursWorked > 40); The midterm grade is less than 50. failedMidterm = (midtermGrade < 50); 45 hoursWorked true workedOvertime 95 midtermGrade false failedMidterm

62 Complex Expressions Break complex expressions down
boolean failedMidterm, failedFinal, …; failedMidterm = (midtermGrade < 50); failedFinal = (finalGrade < 50); failedBothTests = failedMidterm && failedFinal; blewOffLabs = (labGrade < 30); blewOffAsgns = (asgnGrade < 30); blewOffWork = blewOffLabs && blewOffAsgns; if (failedBothTests || blewOffWork) { System.out.println("Special fail rule!"); courseGrade = "F"; }

63 Boolean Methods equals/IgnoreCase and startsWith are methods
they’re String methods  ask any String They return a boolean value true or false can be saved in a variable or used directly We can create our own boolean methods if (userSaysYes("Do you want fries with that?")) { order.add("fries"); } how does NetBeans know it’s a boolean method?

64 Boolean Methods boolean methods return boolean value
private static boolean userSaysYes(String q) { Scanner kbd = new Scanner(System.in); String answer; System.out.print(q + " "); answer = kbd.next(); kbd.nextLine(); return isYes(answer); } how does NetBeans know isYes is a boolean method?

65 Boolean Methods boolean methods return boolean value
private static boolean isYes(String word) { return word.equalsIgnoreCase("yes") || word.equalsIgnoreCase("yeah") || word.equalsIgnoreCase("sure") || word.equalsIgnoreCase("ok") || word.equalsIgnoreCase("fine"); } the expression can be as complicated as you want

66 Questions


Download ppt "The “if” Control Sections 3.1 & 3.2"

Similar presentations


Ads by Google