Presentation is loading. Please wait.

Presentation is loading. Please wait.

Math 130 Decisions II Wed, Sept 12, 2007 Notes: ref. C. Horstmann, Java Concepts.

Similar presentations


Presentation on theme: "Math 130 Decisions II Wed, Sept 12, 2007 Notes: ref. C. Horstmann, Java Concepts."— Presentation transcript:

1 Math 130 Decisions II Wed, Sept 12, 2007 Notes: ref. C. Horstmann, Java Concepts

2 2 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, floating-point numbers, strings, and objects To recognize the correct ordering of decisions in multiple branches To program conditions using Boolean operators and variables

3 3 Comparing Strings Don't use == for strings! if (input == "Y") // WRONG!!! Use equals method: if (input.equals("Y")) == tests identity, equals tests for equal contents B Smith: 9/25: stopped here w/ morning section B Smith: 9/25: stopped here w/ morning section B Smith: 9/25: stopped here with night section; spent time discussing project and misc questions. B Smith: 9/25: stopped here with night section; spent time discussing project and misc questions. B Smith: 9/27 Stopped her with morning section. Spent time discussing String representation, if and if-else, and the && and || constructs. Also completed this slide. B Smith: 9/27 Stopped her with morning section. Spent time discussing String representation, if and if-else, and the && and || constructs. Also completed this slide.

4 4 Comparing Strings - II Case insensitive test ("Y" or "y") if ( input.equalsIgnoreCase("Y") )

5 5 Comparing Strings – III compareTo() s.compareTo(t) < 0 means: s comes before t in the dictionary “car” comes before “cargo” All uppercase letters come before lowercase:  “Hello” comes before “car”

6 6 Comparing Objects == tests for identity, equals for identical content Rectangle box1 = new Rectangle(5, 10, 20, 30); Rectangle box2 = box1; Rectangle box3 = new Rectangle(5, 10, 20, 30); box1 != box3, but box1.equals(box3) box1 == box2  Caveat: equals must be defined for the class

7 7 Testing for null null reference refers to no object String middleInitial = null; // Not set if (... ) middleInitial = middleName.substring(0, 1); 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 “” B Smith: clarify B Smith: clarify B Smith: Stopped here on 2/7/07 B Smith: Stopped here on 2/7/07

8 8 Your Turn What is the value of s.length() if s is  1. the empty string ""?  2. the string " " containing a space?  3. null?

9 9 Answers  (a) 0;  (b) 1;  (c) an exception is thrown

10 10 Your Turn Which of the following comparisons are syntactically incorrect? Which of them are syntactically correct, but logically questionable? String a = "1"; String b = "one"; double x = 1; double y = 3 * (1.0 / 3); a)a == "1" b)a == null c)a.equals("") d)a == b e)a == x f)x == y g)x - y == null h)x.equals(y)

11 11 Answers Syntactically incorrect: e, g, h. Logically questionable: a, d, f

12 12 do we need the else?

13 13 no else statement

14 14 File EarthquakeTester.java

15 15 File Earthquake.java

16 16 Multiple Alternatives: Sequences of Comparisons if (condition1) statement1; else if (condition2) statement2;... else statement4; The first matching condition is executed Order matters if (richter >= 0) // always passes r = "Generally not felt by people"; else if (richter >= 3.5) // not tested r = "Felt by many people, no destruction ";... Don't omit else if (richter >= 8.0) r = "Most structures fall"; if (richter >= 7.0) // omitted else--ERROR r = "Many buildings destroyed

17 17 Multiple Alternatives: Nested Branches Branch inside another branch if (condition1) { if (condition1a) statement1a; else statement1b; } else statement2;

18 Math 130 Decisions III Friday, Sept 14, 2007 Notes: ref. C. Horstmann, Java Concepts

19 19 Compound if() Recall the syntax for an if statement: if (expression) statement1; ● Recall the syntax for an if-else statement: if (expression) statement1; else statement2; ● Note that only a single statement is permitted, but that single statement may be bracketed to form a compound statement B Smith: 2/2/2005 9:56 AM: Start here Friday B Smith: 2/2/2005 9:56 AM: Start here Friday B Smith: This should be L07 from here on for Fall05. L07 should be if-else, switch, while, and scanf. L08 should be B Smith: This should be L07 from here on for Fall05. L07 should be if-else, switch, while, and scanf. L08 should be

20 20 Compound if-else The if-else statement: ● The compound if-else if (expression) statement1; else statement2; ● Note that only a single statement is permitted after if, but that single statement may be bracketed to form a compound statement if (expression) { statement1; statement2; statement3; } else statement4;

21 21 Nested if statement In general, any statement can be replaced with multiple statements in braces We can nest the if 's to form a multi-condition if scenario, changing this: if (myMoney < 5.0) printf(“I'm nearly broke”); else printf(“ I have more than 5 dollars.”); ● To something like this: if (myMoney 3) printf(“I'm broke but I can buy a latte”); } else printf(“ I have more than 5 dollars.”);

22 22 Nested if statement (cont'd) Braces in this statement are important if (myMoney 3) printf(“I'm broke but I can buy a latte”); } else printf(“ I have more than 5 dollars.”); ● The same statement without braces would be evaluated as if (myMoney 3) printf(“I'm broke but I can buy a latte”); else printf(“ I have more than 5 dollars.”); ● The else is associated with the nearest if!

23 23 if-else chain Remember, statement can be any legitimate Java statement ● The compound if-else if (expression) statement1; else statement2; ● Note that only a single statement is permitted after if, but that single statement may be bracketed to form a compound statement if (expression) { statement1; statement2; statement3; } else statement4;

24 24 Using Boolean Expressions: The boolean Type George Boole (1815-1864): pioneer in the study of logic value of expression amount < 1000 is true or false. boolean type: one of these 2 truth values

25 25 Using Boolean Expressions: Predicate Method A predicate method returns a boolean value public boolean isOverdrawn() { return balance < 0; } Use in conditions if (harrysChecking.isOverdrawn())...

26 26 Predicate Methods II Useful predicate methods in Character class: isDigit isLetter isUpperCase isLowerCase if (Character.isUpperCase(ch))...

27 27 Predicate Methods II Making code less fragile Useful predicate methods in Scanner class: hasNextInt() and hasNextDouble() if (in.hasNextInt()) n = in.nextInt();

28 28 Truth Tables AND, OR, NOT

29 29 Using Boolean Expressions: The Boolean Operators && and || or ! not if (0 < amount && amount < 1000)... if (input.equals("S") || input.equals("M"))...

30 30 Using Boolean Variables private boolean married; Set to truth value: married = input.equals("M");

31 31 Use in conditions: if (married)... else... if (!married)... Also called flag

32 32 Reduce booleans It is unnecessary to write a test such as if (married == true)... // Don't Just use the simpler test if (married)...

33 33 Self Check When does the statement System.out.println (x > 0 || x < 0); print false ? Rewrite the following expression, avoiding the comparison with false : if (Character.isDigit(ch) == false)...

34 34 Answers When x is zero if (!Character.isDigit(ch))...

35 35 The switch statement The earlier series of if-else statements can get pretty hairy when checking multiple conditions.  Imagine checking user input for a number of possible entries: String input = keyboard.nextLine(); char ch = input.charAt(0); System.out.println(“character entered is : “); if (ch == 'a') System.out.println(“the letter a”); else if (ch == 'b') System.out.println(“the letter b”); else if (ch == 'c') System.out.println(“the letter c”); else if (ch == 'd') System.out.println(“the letter d”); else if (ch == 'e') System.out.println(“the letter e”);. B Smith: Point out that the text has an error in the source code. B Smith: Point out that the text has an error in the source code. B Smith: What does current pedagogy say regarding the teaching of switch? Should it be included? B Smith: What does current pedagogy say regarding the teaching of switch? Should it be included?

36 36 The switch statement (cont'd) One option is to use the switch statement char ch; System.out.println(“character entered is : “); switch (ch) { case 'a' : System.out.println(“the letter a”); break ; case 'b': System.out.println(“the letter b”); break; case 'c': System.out.println(“the letter c”); break; default: System.out.println(“Invalid entry”); } Note the colon! ‘default:’ When none of the cases are met. Good practice for unexpected conditions B Smith: Point out the efficiency advantages. A switch uses the “decide and jump to” algorithm vs looking at EVERY single condition! B Smith: Point out the efficiency advantages. A switch uses the “decide and jump to” algorithm vs looking at EVERY single condition!

37 37 The switch statement (cont'd) You can use the switch statement with multiple scenarios, or cases switch (number) { case 1: System.out.println(“You like peaches”); break; case 2: System.out.println(“You like oranges”); break; case 3: case 4: case 5: System.out.println(“You like Fuji, Gala, or Washington apples”); break; default: System.out.println(“You chose an unknown snack”); } Multiple cases


Download ppt "Math 130 Decisions II Wed, Sept 12, 2007 Notes: ref. C. Horstmann, Java Concepts."

Similar presentations


Ads by Google