Making Choices The “if” Control Sections 3.1 & 3.2
Overview n The “if” control n The “if-else” control n Boolean expressions n Boolean variables n Comparing Strings
Program Flow n Our programs so far have made no choices list (sequence) of commands:list (sequence) of commands: »do the first command »next do the second command »next do the third command »... »finally do the last command n Sometimes need to choose what action to carry out
Making a Choice n Taking a lunch order at Greesieberger’s ask what sandwich they wantask what sandwich they want add that sandwich to the orderadd that sandwich to the order ask if they want fries with thatask if they want fries with that if they do, add fries to the orderif they do, add fries to the order ask what drink they wantask what drink they want add that drink to the orderadd that drink to the order Sometimes fries are added to the order; sometimes they’re not. Depends on what the user said!
Conditional Commands n “Add fries to the order” is conditional computer doesn’t always do thatcomputer doesn’t always do that n “the user wants fries” is the condition if it’s true, then computer adds friesif it’s true, then computer adds fries n In English/pseudocode: “if the user wants fries, then add fries to the order”“if the user wants fries, then add fries to the order” n How to write that in Java?
The “if” Control n Java syntax: if (condition) { conditionalAction; } if (condition) { conditionalAction; } note bracesnote braces »go around the command you maybe want to do note indentation:note indentation: »conditional action indented another four spaces! also note: no semi-colon on the “if” linealso note: no semi-colon on the “if” line »“if you want fries” is not a command if (userWantsFries) { order.add("fries"); order.add("fries");}
“if” Control Example int grade; System.out.print(“What grade did you get? ”); grade = kbd.nextInt(); kbd.nextLine(); if (grade < 50) { System.out.println(“I’m sorry. You failed.”); } What grade did you get? 41 I’m sorry. You failed. What grade did you get? 95 did itdidn’t do it Condition Conditional Action
Simple Comparisons a == b a is equal to b a == b a is equal to b a != b a is not equal to b a != b a is not equal to b a < b a is less than b a < b a is less than b a <= b a is less than or equal to b a <= b a is less than or equal to b a > b a is greater than b a > b a is greater than b a >= b a is greater than or equal to b a >= b a is greater than or equal to b Note: a == b IS a equal to b? a = b MAKE a equal to b!
Exercises n Write if statements: if grade is greater than or equal to 50, print out “You passed!”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 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 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.if y plus 9 is less than or equal to x times 2, set z equal to zero.
“if” Control Longer Example n Control can have multiple commands if (grade < 50) { System.out.println(“I’m sorry. You failed.”); System.out.println(“You cannot go on to 1227.”); } What grade did you get? 41 I’m sorry. You failed. You cannot go on to What grade did you get? 95 grade < 50grade >= 50
Sequential “if” Controls n Each “if” is separate if (grade < 90) { System.out.println(“You didn’t get an A+.”); } if (grade >= 50) { System.out.println(“You didn’t fail.”); } What grade did you get? 41 You didn’t get an A+. What grade did you get? 95 You didn’t fail. What grade did you get? 75 You didn’t get an A+. You didn’t fail. oneother both
Sequential “if” Controls n 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! What grade did you get? 75 oneother neither
Sequential “if” Controls n Each “if” is separate if (midtermGrade < 50) { System.out.println(“You failed the midterm!”); System.out.println(“You failed the midterm!”);} if (finalGrade < 50) { System.out.println(“You failed the final!”); System.out.println(“You failed the final!”);} You failed the midterm!You failed the final! oneother neither You failed the midterm! You failed the final! both
Exercise n What is the output of the following code? int age = 24; int height = 160; int weight = 70; int income = 12000; if (age > 65) {System.out.println("Old!"); } if (height < 160) { System.out.println("Short!"); } if (weight > 100) {System.out.println("Fat!"); } if (income < 30000) { System.out.println("Poor!"); }
The “if-else” Control n Do exactly one of two things if (grade < 50) { System.out.println(“You cannot continue to 1227.”); } else { System.out.println(“You can continue to 1227!”); } What grade did you get? 41 You cannot continue to What grade did you get? 95 You can continue to 1227! oneother
The “if-else” Control n Java syntax: if (condition) { ifSoAction; ifSoAction; } else { otherwiseAction; otherwiseAction;} n Does exactly one of those two things two-way choicetwo-way choice »do this or do that “if” is one-way choice“if” is one-way choice »do this or not
“if” or “if-else”? n Look at the possible outcomes: outcome #1outcome #1 »computer prints A B C D outcome #2outcome #2 »computer prints A D code:code: System.out.print(“A ”); if (condition) { System.out.print(“B ”); System.out.print(“C ”); } System.out.print(“D ”); Sometimes prints B and C; Sometimes doesn’t: (if control)
“if” or “if-else”? n Look at the possible outcomes: outcome #1outcome #1 »computer prints A B D outcome #2outcome #2 »computer prints A C D code:code: System.out.print(“A ”); if (condition) { System.out.print(“B ”); } else { System.out.print(“C ”); } System.out.print(“D ”); Sometimes prints B; Sometimes prints C: (if-else control)
Be Careful with if + if-else n Remember: separate controls done separately What gets printed if age == 15?What gets printed if age == 15? if (age < 18) { System.out.println(“Children’s price”); System.out.println(“Children’s price”);} if (age >= 65) { System.out.println(“Seniors’ price”); System.out.println(“Seniors’ price”);} else { System.out.println(“Regular price”); System.out.println(“Regular price”);} Are you sure???Are you sure??? We’ll talk more about this in a couple of weeks Children’s price Regular price
Exercise n Possible outcomes: outcome #1: A, B, C, E, Foutcome #1: A, B, C, E, F outcome #2: A, D, E, Foutcome #2: A, D, E, F What is the code?What is the code? n Possible outcomes: outcome #1: A, B, C, Doutcome #1: A, B, C, D outcome #2: A, Boutcome #2: A, B What is the code?What is the code?
Exercise n Possible outcomes: outcome #1: A, B, C, F, Goutcome #1: A, B, C, F, G outcome #2: A, D, E, F, Goutcome #2: A, D, E, F, G outcome #3: A, B, C, Foutcome #3: A, B, C, F outcome #4: A, D, E, Foutcome #4: A, D, E, F What is the code?What is the code?
Logical Operators p && q p and q both true p && q p and q both true (0 < n) && (n < 100) p || q either p or q (or both) are true p || q either p or q (or both) are true (m > 0) || (n > 0) !p p is not true !p p is not true!workedOvertime
On Translating from English n In English we can leave things unsaid if x is greater than 0 and less than 100,...if x is greater than 0 and less than 100,... n In Java, we can’t if (x > 0 && 0 && < 100) computer: Huh?? n Start by saying the whole thing in English if x is greater than 0 and x is less than 100,...if x is greater than 0 and x is less than 100,... if (x > 0 && x 0 && x < 100)computer: OK
Warnings n Use the right operators == not = && not & || not | n Nothing goes without saying! a > 0 && a 0 && 0 && a 0 && < 10 b == 0 || c == 0 not b || c == 0 0 < d && d < 10 not 0 < d < 10
Exercises n Write Boolean expressions for whether… x is greater than 0 and y is less than 5x is greater than 0 and y is less than 5 x is greater than zero or y is equal to zx is greater than zero or y is equal to z it’s not the case that x is greater than the product of y and zit’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 zy is greater than x and less than z x is equal to y but not to zx is equal to y but not to z m or n is greater than 0m or n is greater than 0
Boolean Variables n Can save the answer to a comparison use a boolean variableuse a boolean variable boolean workedOvertime = (hours > 40); »you don’t need parentheses, but it’s easier to read n Can use the saved result as a condition if (workedOvertime) { overtimeHours = hours – 40; regularPay = 40 * rate; overtimePay = overtimeHours * rate * 1.5; }
Boolean Variable n Answer to a “True or False” question True or False? a)The hours worked is over 40. boolean workedOvertime = (hoursWorked > 40); a)The midterm grade is less than 50. boolean failedMidterm = (midtermGrade < 50); 45 hoursWorked 95 midtermGrade true workedOvertime false failedMidterm ? ?
Complex Expressions n Break complex expressions down boolean failedMidterm = (midtermGrade < 50); boolean failedFinal = (finalGrade < 50); boolean failedBothTests = failedMidterm && failedFinal; boolean blewOffLabs = (labGrade < 30); boolean blewOffAsgns = (asgnGrade < 30); if (failedBothTests || (blewOffLabs && blewOffAsgns)) { System.out.println("Special fail rule!"); courseGrade = "F"; }
Exercise n Create boolean variables as follows senior: age is 65 or moresenior: age is 65 or more over55: age is 55 or moreover55: age is 55 or more disabled: (read from user)disabled: (read from user) »nextInt reads an int, nextDouble reads a double… »…what is the method to read a boolean called? eligibleForPension:eligibleForPension: »seniors are eligible »disabled people over 55 are eligible »(no one else is eligible)
Choosing Fries n Ask the user: Do you want fries with that? n Get user’s answer (should be yes or no) n if the answer was yes, add fries to the order n In Java (but not right) System.out.println(“Do you want fries?”); String answer = kbd.next(); kbd.nextLine(); if (answer == “yes”) …
Object Variables n Strings are objects == means “Are they the very same object?” as in “My car and my wife’s car are the same car”== 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”want “Are they the same value?” as in “I have the same car as my neighbour” My CarMy Wife’s CarMy Neighbour’s Car The String in the codeWhat the user typed in “yes”
Comparing Strings n Strings are objects usual comparison operators (==,,..) don’t work the way we wantusual comparison operators (==,,..) don’t work the way we want n Strings know how to compare themselves to other strings – comparison methods oneString.equals(anotherString)oneString.equals(anotherString) oneString.equalsIgnoreCase(anotherString)oneString.equalsIgnoreCase(anotherString) oneString.compareTo(anotherString)oneString.compareTo(anotherString)
String Equality n Strings are equal if exactly the same “First String”.equals(“First String”)“First String”.equals(“First String”) n Any other strings are different! ! “First String”.equals(“Second String”)! “First String”.equals(“Second String”) ! “First String”.equals(“first string”)! “First String”.equals(“first string”) ! “First String”.equals(“FirstString”)! “First String”.equals(“FirstString”) NOTequals
Choosing Fries n In Java System.out.println(“Do you want fries?”); String answer = kbd.next(); kbd.nextLine(); if (answer.equals(“yes”)) … only accepts “yes”only accepts “yes” does not accept “Yes”, “YES”, …does not accept “Yes”, “YES”, …
String.equalsIgnoreCase n Sometimes don’t care if capital or small “First String”.equalsIgnoreCase(“First String”)“First String”.equalsIgnoreCase(“First String”) “First String”.equalsIgnoreCase(“first string”)“First String”.equalsIgnoreCase(“first string”) n Any other strings are different! ! “First String”.equalsIgnoreCase(“Second String”)! “First String”.equalsIgnoreCase(“Second String”) ! “First String”.equalsIgnoreCase(“FirstString”)! “First String”.equalsIgnoreCase(“FirstString”) NOTequals (ignoring case)
Choosing Fries n In Java System.out.println(“Do you want fries?”); String answer = kbd.next(); kbd.nextLine(); if (answer.equalsIgnoreCase(“yes”)) … accepts “yes”, “Yes”, “YES”, …accepts “yes”, “Yes”, “YES”, … (does not accept “yeah”)(does not accept “yeah”)
String.startsWith n 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”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.
String.toUpperCase/toLowerCase n 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”, …now accepts “Yes”, “yes”, “Yeah, “yup”, … »upperAnswer is “YES”, “YES”, “YEAH”, “YUP” »answer is still “Yes”, “yes”, “Yeah”, “yup”
String.oneThing().another() n Can combine two steps into one and more, if you wantand 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”if answer is “yes”, then answer.toUpperCase() is “YES”, and that does start with a “Y”
Exercise n Code above treats “sure” as “no” it doesn’t start with “Y” or “y”it doesn’t start with “Y” or “y” n 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 nobig N or little n both count as no if (answer.toUpperCase().startsWith(“Y”)) ???
Looking Ahead n equals, equalsIgnoreCase, startsWith, etc. are called “methods” they’re “String methods” they attach to Stringsthey’re “String methods” they attach to Strings “Some string” (dot) someMethod ()“Some string” (dot) someMethod () n print and println are also methods they attach to System.outthey attach to System.out n nextInt and nextDouble are methods, too they attach to Scannersthey attach to Scanners
Looking Ahead n Method commands all have the same form someThing (dot) someMethod (arguments)someThing (dot) someMethod (arguments)System.out.println(“Hello”)answer.startsWith(“Y”) the arguments are in parenthesesthe arguments are in parentheses »argument = extra information the method needs the parentheses must be there…the parentheses must be there… …even if there are no arguments…even if there are no argumentskbd.nextInt()
Looking Ahead n main is also a method it’s a special method that the computer knows is “the main thing this program does”it’s a special method that the computer knows is “the main thing this program does” n Later we’ll learn to make more methods more than one method in the classmore than one method in the class »can call the methods in our own class »can call methods in one class from another class n For now, just notice the method calls try to understand what they dotry to understand what they do
Questions