530 likes | 681 Views
Making Choices. The “if” Control Sections 3.1 & 3.2. Overview. More on input The “if” control The “if-else” control Boolean expressions Boolean variables Comparing Strings. Input in Java. Tell the computer we’ll be using a Scanner import java.util.Scanner ;
E N D
Making Choices The “if” Control Sections 3.1 & 3.2
Overview • More on input • The “if” control • The “if-else” control • Boolean expressions • Boolean variables • Comparing Strings
Input in Java • Tell the computer we’ll be using a Scanner import java.util.Scanner; • Create the scanner we will use Scanner keyboard = new Scanner(System.in); • Prompt for input System.out.print("Enter a number: "); • Ask the scanner for the next piece of input int n = keyboard.nextInt(); double x = keyboard.nextDouble();
Input & Output on the Monitor • Input & output mixed together on the screen Enter a number: 32 Enter another number: 47 Their sum is 79. • White = produced by System.out • Blue = typed by user, read by keyboard • Note: two separate “streams”! • computer will not read the 79—it’s output
The Two Streams • Computer prints User types Enter a number: (pause)32 Enter another: (pause)47 Their sum is 79. • Computer pauses when it needs more input • End of a number indicated by • enter/return ( on diagram above) • or anything that’s not part of a number System.out System.in
Anticipating the Computer • Computer prints User types Enter a number: (pause)32 47 Enter another: Their sum is 79. • Two numbers on first line (space between) • Second number already in stream when computer gets to second input command • Computer will not pause before reading 2nd # • Don’t need/get to type the 2nd
Preventing Anticipation • nextLine method reads everything up to and including the next character System.out.print(“Enter a number: ”); n1 = keyboard.nextInt(); keyboard.nextLine(); System.out.print(“Enter another: ”); n2 = keyboard.nextInt(); keyboard.nextLine(); Enter a number: (pause)32 47 Enter another: (pause)55 Their sum is 87.
Question • Where did the 47 go? • we read it, but we didn’t put it anywhere (no assignment command) • computer read it, then immediately forgot it • What did the second nextLine read & forget? Enter a number: (pause)32 47 Enter another: (pause)55 Their sum is 87.
Pausing for ENTER • Can use nextLine to pause input • wait for user to press ENTER System.out.print(“Press ENTER to continue”); keyboard.nextLine(); Press ENTER to continue(pause) • Except…. • What if there’s already a in the input stream?
Pausing for ENTER • What if there’s already a in the input stream? System.out.print(“Enter a number: ”); n2 = keyboard.nextInt(); System.out.print(“Press ENTER to continue”); keyboard.nextLine(); Enter a number: (pause)32 Press ENTER to continue: Computer does not pause. WHY NOT?
Tidying Up As You Go Along • Use nextLine() whenever you expect the user to press the ENTER key • gets rid of the and everything before it • makes sure that your next input statement gives the user a chance to type something
Exercise • Write commands to • prompt for length • read length (double value) • prompt for width • read width (double value) • echo back length and width • pause for user to press enter key • Make sure numbers entered separately • then change so numbers entered on one line
Reading Strings • You can save the lines you read String line; System.out.print("Enter a line: "); line = keyboard.nextLine(); System.out.print("You said \"" + line + "\""); • here we put the stuff we read into a variable (Note: the character doesn’t get saved) Note the “escape sequence” \" which lets you put quotation marks inside quotation marks.
w1 w1 w2 w2 ? “two” ? “words” Reading Strings • You can also read Strings word by word String w1, w2; System.out.print("Enter two words: "); w1 = keyboard.next(); w2 = keyboard.next(); keyboard.nextLine(); // tidy up! Note: NOT nextWord()! Enter two words: two words
Exercise • Write code to read in a person’s name… • first name (one word) and last name (one word) • …then print out their name in this format: • Last, First • …then pause for user to press Enter What is your full name? Mark Young Young, Mark Press ENTER to continue...
Program Flow • Our programs so far have made no choices • list (sequence) of commands: • do the first command • next do the second command • next do the third command • ... • finally do the last command • Sometimes need to choose what action to carry out
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 do, 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 said!
Conditional Commands • “Add fries to the order” is conditional • computer doesn’t always do that • “the user wants fries” is the condition • if it’s true, then computer adds fries • In English/pseudocode: • “if the user wants fries, then add fries to the order” • How to write that in Java?
The “if” Control • Java syntax: if (condition){conditionalAction;} • note indentation: • conditional action indented another four spaces! • also note: no semi-colon on the “if” line • “if you want fries” is not a command if (userWantsFries) { 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.”); } Condition Conditional Action What grade did you get? 41 I’m sorry. You failed. What grade did you get? 95 did it didn’t do it
Simple Comparisons • 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 Note: two equals signs compare one equals sign assign
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 not equal to secretNumber, print out “That’s not it!” • if y plus 9 is less than or equal to x squared, print out “That’s not above the parabola!”
“if” Control Longer Example • 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 1227. What grade did you get? 95 grade < 50 grade >= 50
Sequential “if” Controls • 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. one other What grade did you get? 75 You didn’t get an A+. You didn’t fail. both
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 (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 = 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 • 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 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
“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 (condition) { 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 (condition) { System.out.print(“B ”); } else { System.out.print(“C ”); } System.out.print(“D ”);
Be Careful with if + if-else • Remember: separate controls done separately • What gets printed if age == 15? if (age < 18) { System.out.println(“Children’s price”); } if (age >= 65) { System.out.println(“Seniors’ price”); } else { System.out.println(“Regular price”); } • Are you sure??? Children’s price Regular price We’ll talk more about this in a couple of weeks
Exercise • Possible outcomes: • outcome #1: A, B, C, E, F • outcome #2: A, D, E, F • What is the code? • Possible outcomes: • outcome #1: A, B, C, D • outcome #2: A, B • What is the code?
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?
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 !workedOvertime
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 ==not= &¬& ||not| • Nothing goes without saying! a > 0 && a < 10nota > 0 && < 10 b == 0 || c == 0notb || c == 0 0 < d && d < 10not0 < 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 • 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
Boolean Variables • Can save the answer to a comparison • use a boolean variable booleanworkedOvertime = (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. booleanworkedOvertime = (hoursWorked > 40); • The midterm grade is less than 50. booleanfailedMidterm = (midtermGrade < 50); workedOvertime midtermGrade failedMidterm hoursWorked ? 45 95 true false ?
Complex Expressions • Break complex expressions down booleanfailedMidterm = (midtermGrade < 50); booleanfailedFinal = (finalGrade < 50); booleanfailedBothTests = failedMidterm && failedFinal; booleanblewOffLabs = (labGrade < 30); booleanblewOffAsgns = (asgnGrade < 30); if (failedBothTests || (blewOffLabs && blewOffAsgns)) { System.out.println("Special fail rule!"); courseGrade = "F"; }
Exercise • Create boolean variables as follows • senior: age is 65 or more • over55: age is 55 or more • disabled: (read from user) • what is the method to read a boolean called? • eligibleForPension: • seniors are eligible • disabled people over 55 are eligible • (no one else is eligible)
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.println(“Do you want fries?”); String answer = kbd.next(); kbd.nextLine(); if (answer == “yes”) …
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 • Strings are objects • usual comparison operators (==, <, >, ..) don’t work the way we want • Strings know how to compare themselves to other strings – comparison methods • oneString.equals(anotherString) • oneString.equalsIgnoreCase(anotherString) • oneString.compareTo(anotherString)
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 • want to accept little Ys, too System.out.println(“Do you want fries?”); String answer = kbd.next(); kbd.nextLine(); if (answer.toUpperCase().startsWith(“Y”)) … • there’s also an endsWith method Later we’ll see how to make sure the user answers with a yes or no