The “if” Control Sections 3.1 & 3.2

Slides:



Advertisements
Similar presentations
Logic & program control part 2: Simple selection structures.
Advertisements

CS 106 Introduction to Computer Science I 09 / 25 / 2006 Instructor: Michael Eckmann.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)
Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators, Constants, and Switching int and double)
Making Choices The “if” Control Sections 3.1 & 3.2.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Decision Structures and Boolean Variables. Sequence Structures Thus far, we’ve been programming “sequence structures” Thus far, we’ve been programming.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Decisions, Decisions, Decisions Conditional Statements In Java.
CSCI 1226 FALL 2015 MIDTERM #1 REVIEWS.  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice, keyboards,
Methods II Material from Chapters 5 & 6. Note on the Slides  We have started to learn how to write non- program Java files  classes with functions/methods,
Review of CSCI 1226 What You Should Already Know.
Control Statements: Part1  if, if…else, switch 1.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Nested Structures Chapters 3 & 4. Outline n Conditionals inside loops n Conditionals inside conditionals n If-else-if controls n Loops inside loops n.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
CS0007: Introduction to Computer Programming
JavaScript Controlling the flow of your programs with ‘if’ statements
Introduction to Decision Structures and Boolean Variables
CMSC201 Computer Science I for Majors Lecture 03 – Operators
Excel IF Function.
CS0007: Introduction to Computer Programming
COMP 14 Introduction to Programming
Introduction to Python
Boolean expressions and if-else statements
Line Continuation, Output Formatting, and Decision Structures
Selection (also known as Branching) Jumail Bin Taliba by
OBJECT ORIENTED PROGRAMMING I LECTURE 8 GEORGE KOUTSOGIANNAKIS
CHAPTER 4 Selection CSEG1003 Introduction to Computing
WELCOME to….. The If Statement.
Chapter 3 Selections ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH Introduction to Java Programming, Liang (Pearson 2014)
Programming Mehdi Bukhari.
EGR 2261 Unit 4 Control Structures I: Selection
Debugging and Random Numbers
Intro to C Tutorial 4: Arithmetic and Logical expressions
Boolean Expressions and If
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Repeating Actions The "while" and "for" Controls Sections 4.1 & 4.2
CMSC201 Computer Science I for Majors Lecture 03 – Operators
Control Structures – Selection
Boolean Expressions And if…else Statements.
Control Statement Examples
Building Java Programs
Building Java Programs
Conditionals & Boolean Expressions
Conditionals & Boolean Expressions
Line Continuation, Output Formatting, and Decision Structures
Conditional Statements
Conditions and Ifs BIS1523 – Lecture 8.
TIPS: How to Be Successful
Outline Boolean Expressions The if Statement Comparing Data
Java Programming Control Structures Part 1
Chapter 5: Control Structure
Introduction to Decision Structures and Boolean Variables
SE1H421 Procedural Programming LECTURE 4 Operators & Conditionals (1)
Chapter 2 Programming Basics.
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
CHAPTER 5: Control Flow Tools (if statement)
Chapter 3: Selection Structures: Making Decisions
CSC 1051 – Data Structures and Algorithms I
Unit 3: Variables in Java
Building Java Programs
Just Enough Java 17-May-19.
Conditionals and Loops
Announcements Program 1 due noon Lab 1 due noon
What You Should Already Know
Presentation transcript:

The “if” Control Sections 3.1 & 3.2 Making Choices The “if” Control Sections 3.1 & 3.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

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.

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?

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.

“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

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!

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 !

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.

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

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

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

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

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.

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 != !

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"

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.

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

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”, …

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)

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

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.

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”

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”

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”

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"))  ???

The “if-else” Control 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! "); } 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

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

Better Than Two if Controls Could rewrite if-else into two if controls: if (grade < 50) { System.out.println("You cannot continue to 1227. "); } 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

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

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 1228. "); } if (grade >= 50) { System.out.println("You can continue to 1228! "); what went wrong?

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

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

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

“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 ");

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

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?

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' !

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

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!

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

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

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!

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

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

Eligible for Pension // ask age System.out.print("How old are you? "); age = kbd.nextInt(); kbd.nextLine(); eligible = (age >= 65); // if 55..64, 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"); }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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"; }

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?

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?

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

Questions