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

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

Dec 18, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Math 130 Decisions II Wed, Sept 12, 2007 Notes: ref. C. Horstmann, Java Concepts.

Math 130

Decisions IIWed, Sept 12, 2007

Notes: ref. C. Horstmann, Java Concepts

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

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

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

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.

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

4

Comparing Strings - II

• Case insensitive test ("Y" or "y")if ( input.equalsIgnoreCase("Y") )

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

5

Comparing Strings – IIIcompareTo()

• 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”

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

6

Comparing Objects

== tests for identity, equals for identical contentRectangle 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

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

7

Testing for null

• null reference refers to no object String middleInitial = null; // Not setif ( . . . ) 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:

clarifyB Smith:

Stopped here on 2/7/07

B Smith:

Stopped here on 2/7/07

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

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?

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

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 == nullc) a.equals("")d) a == be) a == xf) x == yg) x - y == nullh) x.equals(y)

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

12

do we need the else?

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

13

no else statement

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

14

File EarthquakeTester.java

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

15

File Earthquake.java

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

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 elseif (richter >= 8.0) r = "Most structures fall";if (richter >= 7.0) // omitted else--ERROR r = "Many buildings destroyed

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

17

Multiple Alternatives: Nested Branches

• Branch inside another branchif (condition1){ if (condition1a) statement1a; else statement1b;}else statement2;

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

Math 130

Decisions IIIFriday, Sept 14, 2007

Notes: ref. C. Horstmann, Java Concepts

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

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

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

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;

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

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 < 5.0) { if (myMoney > 3) printf(“I'm broke but I can buy a latte”); }else printf(“ I have more than 5 dollars.”);

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

22

Nested if statement (cont'd)• Braces in this statement are important

if (myMoney < 5.0) { 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 < 5.0) 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!

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

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

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

25

Using Boolean Expressions: Predicate Method

• A predicate method returns a boolean value

public boolean isOverdrawn()

{

return balance < 0;

}

• Use in conditionsif (harrysChecking.isOverdrawn())

. . .

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

26

Predicate Methods II

• Useful predicate methods in Character class:isDigit

isLetter

isUpperCase

isLowerCase

• if (Character.isUpperCase(ch)) . . .

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

27

Predicate Methods II

Making code less fragile

• Useful predicate methods in Scanner class: hasNextInt() and hasNextDouble()

if (in.hasNextInt())

n = in.nextInt();

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

28

Truth Tables

• AND, OR, NOT

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

29

Using Boolean Expressions: The Boolean Operators

• && and• || or• ! not

if (0 < amount && amount < 1000) . . .

if (input.equals("S") || input.equals("M")) . . .

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

30

Using Boolean Variables

private boolean married;

• Set to truth value:married =

input.equals("M");

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

31

Use in conditions:

if (married)

. . .

else . . .

if (!married)

. . .

• Also called flag

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

32

Reduce booleans

• It is unnecessary to write a test such asif (married == true) . . . // Don't

• Just use the simpler testif (married) . . .

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

33

Self Check

• When does the statementSystem.out.println (x > 0 || x < 0);print false?

• Rewrite the following expression, avoiding the comparison with false:

if (Character.isDigit(ch) == false) . . .

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

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?

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

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!

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

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