chapter6 - Chapter 6 Decisions Chapter Goals To be able to...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Chapter 6 Decisions Chapter Goals To be able to implement decisions using if statements To understand how to group statements into blocks To learn how to compare integers, floatingpoint numbers, strings, and objects To recognize the correct ordering of decisions in multiple branches To program conditions using boolean operators and variables Decisions So far, our examples haven't made any decisions The same code gets executed no matter what Assignment 1 Path BankAccount This is called sequential execution Is this how real applications work? Decisions The real world requires decisions Is it time to feed the cat? Can a book be checked out? Essential feature of nontrivial programs is to make decisions based on input The answers to these decision require different actions Introduces the need for control statements If statements Conditional statements are represented with ifthen else statements Scanner stdin = new Scanner(System.in); int testScore = stdin.nextInt(); if (testScore < 70) { System.out.println("You are below the mean"); } else { System.out.println("You are above the mean"); } If Statements: Syntax if (<boolean expression>) { <then block> } else { <else block> } Example withdraw() method we implemented allowed user to withdraw as much money as they wanted Is this realistic? What decision should withdraw() make? What should the decision be based on? Example public void withdraw(double amount){ if (amount <= balance) balance -= amount; } Example Most banks also charge an overdraft penalty, how would we go about changing our example to implement this? The decision we made only resulted in one instruction whichever way we took Most decisions lead to a sequence of instructions (multiple statements). In order to show that the entire sequence of instructions belong to the thenblock (or else block), we group them with curly braces{ } A sequence of instructions surrounded by curly braces is called a block Statements Example if (amount <= balance) { System.out.println("Legal Withdrawal"); balance = balance amount; } else { balance = balance OVERDRAFT_PENALTY; } Statements Block statement a group of statements enclosed within curly braces Methods Classes if statements, switch statements, loops Simple statement Compound statement Basic statement such as balance = balance amount; Statements that have multiple paths of execution If statements, loops If Statements If you have a single statement, { } not required if (testScore < 70) System.out.println("You are below the mean"); else System.out.println("You are above the mean"); But convention to use them anyways Helpful for adding temporary output to check if a branch is executed Makes nested ifelse statements easier to read If Statements: Syntax if(condition) statement if (condition) statement1 else statement2 statement must be a statement simple, compound, or block Use indentation to indicate nesting levels Style public class BankAccount { | ... | public void withdraw() | { | | if (amount <= balance) | | { | | | balance -= amount; | | } | } } Die Example // Declare Die die1 = Die die2 = and new new create Die objects Die(); Die(); // Roll die objects die1.roll(); die2.roll(); // Save results in new variables int roll1 = die1.getTop(); int roll2 = die2.getTop(); Die Example // Test for doubles if ( roll1 == roll2 ) System.out.println( "Doubles" ); // rest of program Die Example roll1 == roll2 false true System.out.println( "doubles!" ); ... continue with rest of program Die Example // Test for doubles if ( roll1 == roll2 ) System.out.println( "Doubles" ); else System.out.println( "Sorry, no doubles" ); // rest of program Die Example roll1 == roll2 false System.out.println( "sorry ..." ); true System.out.println( "doubles!" ); ... continue with rest of program Selection Operator Selection Operator condition ? value1 : value2 If the condition is true, value1 is returned. If the condition is false, value2 is returned. Example: Absolute Value y = (x >= 0) ? x : -x; Booleans boolean is a primitive data type that holds one of two values true false Any time a decision needs to be made, we make that decision using a boolean expression, which evaluates to a boolean value Note: a mathematical expression returns a numerical value Boolean Expressions What operators are used for boolean expressions? < <= > >= == != less than less than or equal to greater than greater than or equal to equal to not equal to Boolean expressions are just like mathematical expressions, but they return true or false (not int, double, etc) Examples: Boolean Expressions 3 * 8 <= 5 * 5 6 % 4 > 0 testScore < 80 testScore * 2 > 350 When the computer reaches an if statement, it first evaluates the boolean expression If that expression is true, the <then block> is executed Otherwise, the <else block> is executed An if statement is called a branching statement because it branches to a block of code If Statements Comparisons Comparing whole numbers is trivial int a = 5; if (a == 5){ System.out.println("Wow this is easy!"); } else { System.out.println("Java really sucks"); } Comparing real numbers is more difficult because we have to take into account roundoff errors. Comparisons double r = Math.sqrt(2); double d = r * r 2; if (d != 0){ System.out.println("Your equation is incorrect, the result is " + d); } Your equation is incorrect, the result is 4.440892098500626E-16 Comparisons This is a problem, since logically the equation makes sense Lesson: Floating point numbers may not be exact Solution: Use range of values that are close enough Should be close to 0 Comparisons To avoid roundoff errors, don't use == or != to compare floatingpoint numbers To compare floatingpoint numbers test whether they are close enough: |x y| final double EPSILON = 1E-14; if (Math.abs(x - y) <= EPSILON) // x is approximately equal to y is a small number such as 1014 Comparisons We can do comparisons with characters as well They work according to ASCII values: char choice = 'Q'; if (choice < 'Z') System.out.println("valid"); else System.out.println("invalid"); What is the output? Side Note: Characters Remember that we said a char is one letter, digit, or symbol that the computer thinks of as a number. We can cast chars to int and vice versa Examples: (int) 'D' -> 68 (char) 106 -> 'j' (char) ('D' + 1) -> 'E' Comparisons Boolean operators can be used on objects, but do they mean the same thing? They probably don't do what you expect... Primitive types vs. reference types (objects) To test two Strings, use equals() method String Comparisons Don't use == for strings! if (input == "Y") // WRONG!!! Use equals method: if (input.equals("Y")) string1.equals(string2); == tests references, .equals() tests contents String Comparisons String s1 = "Robby", s2; s2 = s1; :String 0 R 1 o 2 b 3 b 4 y s1 s2 String Comparisons What is the result of: s1 == s2 :String 0 R 1 o 2 b 3 b 4 y s1 Why? s2 String Comparisons String s1 = "Robby", s2; s2 = "Robby"; :String 0 R 1 o 2 b 3 b 4 y s1 s2 String Comparisons What is the result of: str1 == str2 :String 0 R 1 o 2 b 3 b 4 y str1 Why? str2 String Comparisons String s1 = "Robby", s2; s2 = new String( s1 ); :String 0 R 1 o 2 b 3 b 4 y 0 R :String 1 o 2 b 3 b 4 y s1 s2 String Comparisons What is the result of: s1 == s2 :String 0 R 1 o 2 b 3 b 4 y 0 R :String 1 o 2 b 3 b 4 y Why? s1 s2 String Comparisons What is the result of: s1.equals(s2); :String 0 R 1 o 2 b 3 b 4 y :String Why? 0 R 1 o 2 b 3 b 4 y s1 s2 String Comparisons equalsIgnoreCase can be used to compare strings while ignoring case Case insensitive test ("Y" or "y") if (input.equalsIgnoreCase("Y")) string1.equalsIgnoreCase(string2) // returns boolean compareTo returns a number that tells which string comes before the other in the dictionary 0 indicates that the strings are the same String Comparisons string1.compareTo(string2) Returns < 0 if string1 comes first Returns 0 if they are equal Returns > 1 if string2 comes first Example: "car" comes before "cargo" All uppercase letters come before lowercase: "Hello" comes before "car" Comparisons == tests for identity, equals() for identical content Most classes have an equals() method defined Rectangle box1 = new Rectangle(5, 10, 20, 30); Rectangle box2 = box1; Rectangle box3 = new Rectangle(5, 10, 20, 30); box1 == box3 is false box1 == box2 is true box1.equals(box3)is true Note: equals() must be defined for the class for this to work Null Reference variables store a reference (address) for an actual object What do they store when they haven't been set to refer to an object? null is a Java reserved word to designate that no object has been set for that variable Null Can be used in tests: if (middleInitial == null) System.out.println(firstName + " " + lastName); else System.out.println(firstName + " " + middleInitial + ". " + lastName); Use ==, not equals, to test for null null is not the same as the empty string "" Multiple Alternatives if (score >= 90) System.out.println("Great!"); else if (score >= 80) System.out.println("Good"); else if (testScore >= 70) System.out.println("OK"); else if (testScore >= 60) System.out.println("Passing"); else if (testScore >= 50) System.out.println("Hmm..."); else if (testScore >= 0) System.out.println("Study!"); else Multiple alternatives First condition that is true is the ONLY statement executed Therefore, order matters: if (testScore >= 90) System.out.println("Great!"); else if (testScore >= 80) System.out.println("Good"); else if (testScore >= 70) System.out.println("OK"); Multiple Alternatives Wrong order here causes problems! if (testScore >= 0) System.out.println("Study!"); else if (testScore >= 50) System.out.println("Hmm..."); else if (testScore >= 60) System.out.println("Passing"); Multiple Alternatives if (testScore >= 90) System.out.println("Great!"); if (testScore >= 70) System.out.println("OK"); if (testScore >= 50) System.out.println("Hmm..."); These aren't exclusive statements anymore Else matters!!! Switch Statements switch ( <variable name> ){ <case label 1>: <case body 1> ... <case label n>: <case body n> } Can only be used on integers, characters, or enumerated constants Good for testing multiple values for one expression Switch Statements Switch Statements The break statement causes execution to skip the remaining portion of the switch statement and resume execution following the switch statement. The break statement is necessary to execute statements in one and only one case. Switch Statements switch( c ) { case `y` : case `n' : default } : System.out.println("Yes"); break; System.out.println("No"); break; System.out.println("Invalid entry"); Nested Decisions then and else blocks can contain as many statements as needed These blocks can also have another if statement An if statement inside of another if statement is called a nestedif statement Nested Decisions if (testScore >= 70){ if (studentAge < 10){ System.out.println("You did a great job"); } else { System.out.println("You did pass"); //test score >=70 and age >=10 } } else { //test score < 70 System.out.println("You did not pass"); } Tax Schedule Example Tax Schedule Example Compute taxes due, given filing status and income figure: (1) (2) branch on the filing status for each filing status, branch on income level The twolevel decision process is reflected in two levels of if statements We say that the income test is nested inside the test for filing status if (status == SINGLE) { if (income <= SINGLE_BRACKET1){ tax = RATE1 * income; } else if (income <= SINGLE_BRACKET2){ tax = RATE1 * SINGLE_BRACKET1 + RATE2 * (income - SINGLE_BRACKET1); } else { tax = RATE1 * SINGLE_BRACKET1 + RATE2 * (SINGLE_BRACKET2 -SINGLE_BRACKET1) + RATE3 * (income - SINGLE_BRACKET2); } } else if } } { (income <= MARRIED_BRACKET1){ tax = RATE1 * income; else if (income <= MARRIED_BRACKET2) { tax = RATE1 * MARRIED_BRACKET1 + RATE2 * (income - MARRIED_BRACKET1); else { tax = RATE1 * MARRIED_BRACKET1 + RATE2 * (MARRIED_BRACKET2 - MARRIED_BRACKET1) + RATE3 * (income - MARRIED_BRACKET2); } } Dangling Else There is a good reason we always use curly braces in our programs Very common error can be made: if (testScore >=60) if(testScore <= 80) System.out.println("You are in safe range"); else // Pitfall! System.out.println("You may be in trouble"); Dangling Else Which if statement does the else apply to? Always the closest unclosed if if (testScore >=60) if(testScore <= 80) System.out.println("You are in safe range"); else System.out.println("You may be in trouble"); Using Boolean Expressions Recall that the last primitive that we really haven't said much about is the boolean data type double temp = 100; boolean isHot = temp > 60; System.out.println("Is it hot? Ans: " + isHot); Predicate Methods A predicate method returns a boolean value public boolean isOverdrawn() { return balance < 0; } Use to test conditions just like another other method if (harrysChecking.isOverdrawn()) . . . Predicate Methods Many predicate methods String class: equals() Character class: isUpperCase(), isDigit(), isLetter(), isLetter(), isLowerCase() All of these are public static methods Convention is to prefix "is" or "has" use "set" Much like accessors use "get" and mutators Example Scanner class has a hasNextInt() method which allows you to test if there is an int before you get it (and cause program to crash) Scanner in = new Scanner(System.in); int score; System.out.println("Enter Score"); if(in.hasNextInt()) score = in.nextInt() Boolean Operators What if we want one expression to test multiple conditions? Example: Does a student have a score above 50 and below 75? Need boolean operators Boolean Operators Can use a logical operator to test simultaneously AND true if both are true, false otherwise true if either is true, false otherwise true of the expression is false, false if it is true && || OR ! NOT Boolean Operators Boolean Operators Example if (testScore > 50 && testScore < 75){ System.out.println("In range C to D range"); } Example char c; ... if (!(c == `!')) { System.out.print(c); } Many ways to write one expression: if (age < 0){ System.out.print("valid"); } else { System.out.print("invalid"); } ------------------------------------if (!(age >= 0)){ System.out.print("valid"); } else { System.out.print("invalid"); } ---------------------------------if (age >= 0){ System.out.print("invalid"); } else { System.out.print("valid"); } Order of Operations Like before, boolean operators are evaluated left to right Example: Suppose y has the value 0 // Run time error, divide by // zero // Legal x / y > z || y == 0 y == 0 || x / y > z Precedence Table Precedence 9 8 7 6 5 4 3 2 1 Group subexpression unary multiplicative additive relational equality AND OR assignment Operator ( ) ! * / % + < <= > >= == != && || = Associativity inner to outer left to right right to left left to right left to right left to right left to right left to right left to right right to left Example In math, we represent the range of x as 80 x < 90 How do we represent this as a boolean expression? (Be careful) Boolean Expressions Check validity of data Divide by zero, out or range errors Classify data Test above mean, below mean Flags Store system settings or user preferences Long messages, noise off, debug mode Style Equivalent statements given a boolean isRaining if (isRaining == true) {} if (isRaining) {} //Preferred Use good identifier names isMoving vs. motionStatus isCheckedOut vs. bookStatus MOST COMMON ERROR! if (x = 5) {} ...
View Full Document

This note was uploaded on 08/08/2008 for the course CS 302 taught by Professor Willbenton during the Spring '07 term at University of Wisconsin.

Ask a homework question - tutors are online