Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6 - Decisions. Characters char char primitive data type primitive data type stores a single character stores a single character operations (same.

Similar presentations


Presentation on theme: "Chapter 6 - Decisions. Characters char char primitive data type primitive data type stores a single character stores a single character operations (same."— Presentation transcript:

1 Chapter 6 - Decisions

2 Characters char char primitive data type primitive data type stores a single character stores a single character operations (same as int ) : + - operations (same as int ) : + - special chars (use backslash) : '\n' '\t' '\\' '\'' special chars (use backslash) : '\n' '\t' '\\' '\'' Example Example char c = 'a'; char q = '\''; // stores a single quote char c = 'a'; char q = '\''; // stores a single quote c a q '

3 Practice int i = (int) 'D' char c = (char) 106 i = 'D' + 'A' c = (char)('D' + 42) 68 j 133 ‘n’

4 Chapter Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how to group statements into blocks To understand how to group statements into blocks To learn how to compare integers, floating-point numbers, strings, and objects To learn how to compare integers, floating-point numbers, strings, and objects To recognize the correct ordering of decisions in multiple branches To recognize the correct ordering of decisions in multiple branches To program conditions using Boolean operators and variables To program conditions using Boolean operators and variables

5 Control The real world requires decisions The real world requires decisions Is it time to feed the cat? Can a book be checked out? 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 Essential feature of nontrivial programs is to make decisions based on input The answers to these decision require different actions The answers to these decision require different actions Introduces the need for control statements Introduces the need for control statements

6 Boolean boolean is a primitive data type that holds one of two values boolean is a primitive data type that holds one of two values true true false false Any time a question needs to be asked, we use a boolean expression, which returns a boolean value Any time a question needs to be asked, we use a boolean expression, which returns a boolean value As apposed to a mathematical expression which returns a number value As apposed to a mathematical expression which returns a number value

7 Relational Operators What operators are used for 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

8 Boolean Operators Boolean expressions are just like mathematical expressions Boolean expressions are just like mathematical expressions But here, they return a true or false (not int, double, etc) But here, they return a true or false (not int, double, etc) These are the 6 binary operators These are the 6 binary operators Ex. Ex. testScore < 80 testScore < 80 testScore * 2 > 350 testScore * 2 > 350

9 if statement Conditional statements are represented with if- else statements Conditional statements are represented with if- 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”); }

10 Syntax if ( ){ }else{ }

11 if statements When the code reaches the if statement, it evaluates the boolean expression When the code reaches the if statement, it evaluates the boolean expression If it is true, the is executed If it is true, the is executed If it is false, the is executed If it is false, the is executed Called a branching statement because it branches to a block of code Called a branching statement because it branches to a block of code

12 BankAccount Revisted Withdraw method we implemented allowed user to withdraw as much money as they wanted Withdraw method we implemented allowed user to withdraw as much money as they wanted Is this realistic? Is this realistic? What decision should withdraw() make? What decision should withdraw() make? What should the decision be made on? What should the decision be made on?

13 Version 2.0 public void withdraw(double amount){ if (amount <= balance) balance -= amount; }

14

15 Simple vs. Compound The decision we have made only resulted in one instruction The decision we have made only resulted in one instruction Most decisions lead to a path of instructions, requiring multiple statements. The statements are grouped with curly braces{ } Most decisions lead to a path of instructions, requiring multiple statements. The statements are grouped with curly braces{ } if (amount <= balance) { System.out.println(“Legal Withdrawal”); balance = balance – amount; } else { balance = balance – OVERDRAFT_PENALTY; }

16

17 Productivity Hint 6.1 Style guide – use indentation to indicated nesting levels Style guide – use indentation to indicated nesting levels public class BankAccount { |… |public void withdraw() |{ ||if (amount <= balance) ||{ |||balance -= amount; ||} |} }

18 If statement If you have a single statement, { } not required 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 But convention to use them anyways Helpful for adding temporary output to check if a branch is executed Helpful for adding temporary output to check if a branch is executed Makes nested if-else statements easier to read(later) Makes nested if-else statements easier to read(later) Avoid errors Avoid errors

19 Definition Simple Statement Simple Statement Basic statement such as balance = balance – amount; Basic statement such as balance = balance – amount; Block statement – a group of statements enclosed within curly braces Block statement – a group of statements enclosed within curly braces Methods Methods Classes Classes If statements, Switch, Loops If statements, Switch, Loops Compound statement Compound statement Statements that have multiple paths of execution Statements that have multiple paths of execution If statements, loops If statements, loops

20 Syntax – if statement if(condition) statement if (condition) statement1 else statement2 statement must be a statement - simple, compound, or block

21 Comparing integers Comparing whole numbers is trivial Comparing whole numbers is trivial int a = 5; if (a == 5){ System.out.println(“Wow this is easy!”); } else { System.out.println(“I wanna go home!”); }

22 Comparing Floating Point Comparing real numbers is more difficult when taking into account roundoff errors. Comparing real numbers is more difficult when taking into account roundoff errors. 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

23 Roundoff This is a problem, since logically the equation makes sense This is a problem, since logically the equation makes sense Lesson: Floating point numbers may not be exact Lesson: Floating point numbers may not be exact Solution: Use range of values that can be valued Solution: Use range of values that can be valued Should be close to 0 Should be close to 0

24 To avoid roundoff errors, don't use == to compare floating-point numbers To avoid roundoff errors, don't use == to compare floating-point numbers To compare floating-point numbers test whether they are close enough: |x - y| ≤ ε To compare floating-point 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 10 -14 ε is a small number such as 10 -14

25 if Statement if ( x == y ) { System.out.print( "x equals y"); System.out.print( "x equals y");} In an if statement, the block { } is only executed if the condition expression is true. Indent stmts inside the block.

26 Example Setup // Declare and create Die objects Die die1 = new Die(); Die die2 = new Die(); // Roll die objects die1.roll();die2.roll(); // Save results in new variables int roll1 = die1.getTop(); int roll2 = die2.getTop();

27 Simple if Statement // Test for doubles if ( roll1 == roll2 ) { System.out.println( "Doubles" ); System.out.println( "Doubles" );} // rest of program

28 Control Flow of If statement roll1 == roll2 System.out.println( “doubles!” );... continue with rest of program true false

29 Simple if-else Statement // Test for doubles if ( roll1 == roll2 ) { System.out.println( "Doubles" ); System.out.println( "Doubles" );} else { System.out.println("Sorry, no doubles"); System.out.println("Sorry, no doubles");} // rest of program

30 Control Flow of if-else roll1 == roll2 System.out.println( “doubles!” ); System.out.println( “sorry...” );... continue with rest of program true false

31 Advanced Topic Selection Operator Selection Operator condition ? value1 : value2 If the condition is true, value1 is returned. value2 if the condition false If the condition is true, value1 is returned. value2 if the condition false Ex. Absolute Value y = (x >= 0) ? x : -x;

32 6.3 Multiple Alternatives String r; if (richter >= 8.0) { r = "Most structures fall"; } else if (richter >= 7.0) { r = "Many buildings destroyed"; } else if (richter >= 6.0) { r = "Many buildings considerably damaged, some collapse"; } else if (richter >= 4.5) { r = "Damage to poorly constructed buildings"; } else if (richter >= 3.5) { r = "Felt by many people, no destruction"; } else if (richter >= 0) { r = "Generally not felt by people"; } else { r = "Negative numbers are not valid"; }

33 Multiple alternatives First condition that is true is the ONLY statement executed First condition that is true is the ONLY statement executed Therefore, order matters Therefore, order matters if (testScore >= 90) { System.out.println(“Great!”); } else if (testScore >= 70) { System.out.println(“OK”); } else if (testScore >= 50) { System.out.println(“D’oh!”);}

34 WRONG version if (testScore >= 50) { System.out.println(“D’oh!”); } else if (testScore >= 70) { System.out.println(“OK”); } else if (testScore >= 90) { System.out.println(“Great!”);}

35 Else matters also if (testScore >= 90) System.out.println(“Great!”); if (testScore >= 70) System.out.println(“OK”); if (testScore >= 50) System.out.println(“D’oh!”); Not exclusive statements anymore

36 Adv 6.2 Switch Statement switch ( ){ : :... } Can only be used on integers, characters, or enumerated constants Can only be used on integers, characters, or enumerated constants Good for testing multiple values for one expression Good for testing multiple values for one expression

37

38 The break statement causes execution to skip the remaining portion of the switch statement and resume execution following the switch statement. 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. The break statement is necessary to execute statements in one and only one case.

39

40 Switch statement switch( c )//Some primitive{ case ‘y‘ : System.out.println(“Yes”); break; case ‘n’ :System.out.println(“No”); break; default :System.out.println(“Invalid entry”); }

41 6.3.2 Nested branches then and else blocks can contain as many statements as needed then and else blocks can contain as many statements as needed Can also have another if statement: nested-if statement Can also have another if statement: nested-if statement

42 Example 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”); }

43 Tax Schedule

44 Compute taxes due, given filing status and income figure: Compute taxes due, given filing status and income figure: (1) branch on the filing status (2) for each filing status, branch on income level The two-level decision process is reflected in two levels of if statements The two-level decision process is reflected in two levels of if statements We say that the income test is nested inside the test for filing status We say that the income test is nested inside the test for filing status

45

46 if (status == SINGLE) { if (income <= SINGLE_BRACKET1){ tax = RATE1 * income; } else if (income <= SINGLE_BRACKET2){ tax = RATE1 * SINGLE_BRACKET1 + RATE2 * (income - SINGLE_BRACKET1); + RATE2 * (income - SINGLE_BRACKET1); } else { tax = RATE1 * SINGLE_BRACKET1 + RATE2 * (SINGLE_BRACKET2 -SINGLE_BRACKET1) + RATE3 * (income - SINGLE_BRACKET2); }}

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

48 Dangling else There is a good reason we always use curly braces in our programs There is a good reason we always use curly braces in our programs Very common error can be made: 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”);

49 Boolean Operators What if we want one expression to test multiple conditions What if we want one expression to test multiple conditions Ex. Do they have a score above 50 and below 75? Ex. Do they have a score above 50 and below 75? Need boolean operators Need boolean operators

50 Boolean operators Can use a logical operator to test simultaneously Can use a logical operator to test simultaneously &&ANDtrue if both are true, false otherwise ||ORtrue if either is true, false otherwise !NOTtrue of the expression is false, false if it is true

51 Truth table

52 Example Example if (testScore > 50 && testScore 50 && testScore < 75){ System.out.print(“In range C to D range”); } Example Example char c; … if (!(c == ‘!’){ System.out.print(c);}

53 Many ways to write one expression: 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”);}

54 Precedence Table PrecedenceGroupOperatorAssociativity 9subexpression ( ) inner to outer left to right 8unary ! - right to left 7multiplicative * / % left to right 6additive + - left to right 5relational >= >= left to right 4equality == != left to right 3AND&& 2OR|| 1assignment= right to left

55 Lazy Evaluation Like before, operations evaluated left to right Like before, operations evaluated left to right If one part will make the whole expression false, quit early If one part will make the whole expression false, quit early Ex. y = 0; x / y > z && y != 0//Run time error, divide by // zero y != 0 && x / y > z//Legal Also called short-circuit evaluation Also called short-circuit evaluation

56 Common Uses Check validity of data Check validity of data Divide by zero, out or range errors Divide by zero, out or range errors Classify data Classify data Test above mean, below mean Test above mean, below mean Flags Flags Store system settings or user preferences Store system settings or user preferences Long messages, noise off, debug mode Long messages, noise off, debug mode

57 Style Equivalent statements give a boolean isRaining Equivalent statements give a boolean isRaining if (isRaining == true){} if (isRaining){}//Preferred Use good identifier names Use good identifier names isMoving vs. motionStatus isMoving vs. motionStatus isCheckedOut vs. bookStatus isCheckedOut vs. bookStatus MOST COMMON ERROR! MOST COMMON ERROR! if (x = 5){} if (x = 5){}

58 6.2.3 Comparing Strings Boolean operators can be used on objects, but do they mean the same thing? Boolean operators can be used on objects, but do they mean the same thing? To test two Strings, use equals() method To test two Strings, use equals() method

59 String equality Don't use == for strings! if (input == "Y") // WRONG!!! Don't use == for strings! if (input == "Y") // WRONG!!! Use equals method: if (input.equals("Y")) Use equals method: if (input.equals("Y"))string1.equals(string2); == tests identity, equals tests equal contents == tests identity, equals tests equal contents

60 equalsIgnoreCase() Case insensitive test ("Y" or "y") if (input.equalsIgnoreCase("Y")) Case insensitive test ("Y" or "y") if (input.equalsIgnoreCase("Y")) string1.equalsIgnoreCase(string2) // returns boolean compareTo returns which string comes before the other in the dictionary compareTo returns which string comes before the other in the dictionary Returns an integer Returns an integer

61 compareTo() string1.compareTo(string2) Returns < 0 if string1 comes first Returns < 0 if string1 comes first Returns 0 if they are equal Returns 0 if they are equal Returns > 0 if string 2 comes first Returns > 0 if string 2 comes first "car"comes before "cargo" "car"comes before "cargo" All uppercase letters come before lowercase: "Hello" comes before "car" All uppercase letters come before lowercase: "Hello" comes before "car"

62 6.2.4 Comparing Objects == tests for identity, equals for identical content == tests for identity, equals for identical content Most classes have an equals() method defined 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 box1 != box3 but box1.equals(box3) box1 == box2 box1 == box2 Caveat: equals must be defined for the class Caveat: equals must be defined for the class

63

64 6.2.4 Testing for null Reference variables store a reference (address) for an actual object 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? What do they store when they haven’t been set to refer to an object? null is a Java reserved word to designate no object set null is a Java reserved word to designate no object set

65 Can be used in tests: 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 Use ==, not equals, to test for null null is not the same as the empty string "" null is not the same as the empty string ""

66 Draw the Memory Diagram String s1 = "Robby", s2; s2 = s1; :String R s1 obby 0 1 2 3 4 s2

67 Equality  What is the result of: s1 == s2 s1 == s2 :String R s1 obby 0 1 2 3 4 s2 == because the variables store the same address true Why?

68 Draw the Memory Diagram String s1 = "Robby", s2; s2 = "Robby"; :String R s1 obby 0 1 2 3 4 s2

69 Equality  What is the result of: str1 == str2 str1 == str2 :String R str1 obby 0 1 2 3 4 str2 == because the variables store the same address true Why?

70 Draw the Memory Diagram String s1 = "Robby", s2; s2 = new String( s1 ); :String R s1 obby 0 1 2 3 4 s2 :String Robby 0 1 2 3 4

71 Equality  What is the result of: s1 == s2 s1 == s2 :String R s1 obby 0 1 2 3 4 :String R s2 obby 0 1 2 3 4 false Why?

72 Equality  What is the result of: s1 == s2 s1 == s2 :String R s1 obby 0 1 2 3 4 :String R s2 obby 0 1 2 3 4 == because the variables store different addresses

73 Equality  How do you compare the contents? :String R s1 obby 0 1 2 3 4 :String R s2 obby 0 1 2 3 4 true Why? s1.equals( s2 )

74 Equality  How do you compare the contents? s1.equals( s2 ) s1.equals( s2 ) :String R s1 obby 0 1 2 3 4 :String R s2 obby 0 1 2 3 4.equals( ) because now the contents are compared by the equals method

75 String  Draw a memory diagram for: String s1 = "Jimmy"; String s2; s2 = s1; s1 = "Bobby"; :String J s1 immy 0 1 2 3 4 ? s2 :String Bobby 0 1 2 3 4

76 String Concatenation The + operator The + operator Draw a memory diagram for: Draw a memory diagram for: String s1 = "Jimmy"; s1 = s1 + "Bobby"; String s1 = "Jimmy"; s1 = s1 + "Bobby"; :String J s1 immy 0 1 2 3 4 :String Bobby 0 1 2 3 4 5 6 7 8 9 Jimmy

77 6.4 Using Boolean Expressions 6.4.1 introduces boolean data type 6.4.1 introduces boolean data type Pioneered by George Boole Pioneered by George Boole double temp = 100; System.out.println(“Is it hot?: ” + (temp > 60));

78 6.4.2 Predicate methods A predicate method returns a boolean value public boolean isOverdrawn() { return balance < 0; } A predicate method returns a boolean value public boolean isOverdrawn() { return balance < 0; } Use to test conditions – just like another other method Use to test conditions – just like another other method if (harrysChecking.isOverdrawn())...

79 Predicate Methods Many predicate methods Many predicate methods String class: equals() String class: equals() Character class: isUpperCase(), isDigit(), isLetter(), isLetter(), isLowerCase() Character class: isUpperCase(), isDigit(), isLetter(), isLetter(), isLowerCase() All public static methods All public static methods Convention is to put prefix “ is ” or “ has ” Convention is to put prefix “ is ” or “ has ” Much like accessors use “ get ” and mutators use “ set ” Much like accessors use “ get ” and mutators use “ set ”

80 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 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()

81 Weight Say we had a weight class with one int parameter “gram” that stores weight in grams. Say we had a weight class with one int parameter “gram” that stores weight in grams. What if we really wanted to compare the amount of grams each Weight object held? What if we really wanted to compare the amount of grams each Weight object held? if (wgt1.getGram() == wgt2.getGram()){..}

82 Better Solution Create methods in our class to handle this problem Create methods in our class to handle this problem String method uses equals( ) method to compare two strings String method uses equals( ) method to compare two strings

83 public class Weight{ private int gram; private int gram;……. public boolean equals(Weight wgt) { public boolean equals(Weight wgt) { boolean result; boolean result; if (this.gram == wgt.gram){ if (this.gram == wgt.gram){ result = true; result = true; } else { } else { result = false; result = false; } return result; return result;}...}


Download ppt "Chapter 6 - Decisions. Characters char char primitive data type primitive data type stores a single character stores a single character operations (same."

Similar presentations


Ads by Google