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

Slides:



Advertisements
Similar presentations
Flow of Control Usually the order of statement execution through a method is linear: one after another flow of control: the order statements are executed.
Advertisements

Logic & program control part 2: Simple selection structures.
Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value.
Python Programming Language
CS0007: Introduction to Computer Programming
Flow Control if, while, do-while Juan Marquez (03_flow_control.ppt)
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.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Introduction to Computer Programming Decisions If/Else Booleans.
If Statements Sections 1.25, Control Structures o All code thus far executes every line of code sequentially o We want to be able to repeat,
School of Computing Science CMT1000 Ed Currie © Middlesex University 1 CMT1000: Introduction to Programming Ed Currie Lecture 5B: Branch Statements - Making.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
COMP 110 Introduction to Programming Mr. Joshua Stough September 19, 2007.
Computer Science 1620 Selection Structures. Write a program that accepts the speed of a vehicle, and determines whether that person is speeding assume.
Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators and Constants)
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
ECS 10 10/8. Outline Announcements Homework 2 questions Boolean expressions If/else statements State variables and avoiding sys.exit(…) Example: Coin.
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
COMP 110: Introduction to Programming Tyler Johnson Feb 2, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Repeating Actions The “while” and “for” Controls Sections 4.1 & 4.2 (Also: Special Assignment Operators, Constants, and Switching int and double)
Rational Expressions and selection structures Relational operators Logical operators Selection structures.
Week 4 - Monday.  What did we talk about last time?  Wrapper classes  if statements.
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
CSC 107 – Programming For Science. Announcements.
Building Java Programs
Chapter 4 Introduction to Control Statements Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else Statements Section 4.
PHY281Flow ControlSlide 1 Decisions In this section we will learn how to make decisions in a Java program  if Statements  if... else Statements  Comparison.
A Simple Quiz: Ask User Functions. By Lana Dyck under the direction of Professor Susan Rodger Duke University June 2009, added Part 2 July 2011.
1 Week 6 Branching. 2 What is “Flow of Control”? l Flow of Control is the execution order of instructions in a program l All programs can be written with.
1 Chapter 3 Selections. 2 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
Chapter 5: Structured Programming
Conditional Execution Chapter 3 Python for Informatics: Exploring Information
Agenda Basic Logic Purpose if statement if / else statement
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/
CS 106 Introduction to Computer Science I 09 / 26 / 2007 Instructor: Michael Eckmann.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson All rights reserved.
Conditionals Opening Discussion zWhat did we talk about last class? zDo you have any questions about the assignment? zPass by value limitations.
CS 106 Introduction to Computer Science I 02 / 01 / 2008 Instructor: Michael Eckmann.
CSCI 1226 FALL 2015 MIDTERM #1 REVIEWS.  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice, keyboards,
Programming Fundamentals. The setw Manipulator setw changes the field width of output. The setw manipulator causes the number (or string) that follows.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
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.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #003 (February 14, 2015)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
CONDITIONALS CITS1001. Scope of this lecture if statements switch statements Source ppts: Objects First with Java - A Practical Introduction using BlueJ,
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.
COMP 14 Introduction to Programming
Debugging and Random Numbers
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,
Conditional Statements
The “if” Control Sections 3.1 & 3.2
Chapter 2 Programming Basics.
Simple Branches and Loops
Unit 3: Variables in Java
Just Enough Java 17-May-19.
What You Should Already Know
Presentation transcript:

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