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

Slides:



Advertisements
Similar presentations
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Advertisements

DECISIONS Chapter 5. The if Statement  Action based on a conditions  If the condition is true, the body of the statement is executed if (amount
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Chapter 5 – Decisions Big Java by Cay Horstmann
Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.
Introduction to Computers and Programming Lecture 6 Professor: Evan Korth New York University.
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
Chapter 5  Decisions 1 Chapter 5 Decisions. Chapter 5  Decisions 2 Chapter Goals  To be able to implement decisions using if statements  To understand.
true (any other value but zero) false (zero) expression Statement 2
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Computer Science A 3: 10/2. Logical Expressions Expressions that has a value which is either true or false. Logical expressions are essential in a program.
If Statement if (amount
Chapter 5 – Decisions Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Logical Operators and Conditional statements
Tutorial 4 Decision Making with Control Structures and Statements Section A - Decision Making JavaScript Tutorial 4 -Decision Making with Control.
C++ for Engineers and Scientists Third Edition
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 4 Making.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
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.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
Chapter 5: Decisions. To be able to implement decisions using if statements To understand how to group statements into blocks To learn how to compare.
Chapter 6 - Decisions. Characters char char primitive data type primitive data type stores a single character stores a single character operations (same.
Java Programming Constructs 1 MIS 3023 Business Programming Concepts II The University of Tulsa Professor: Akhilesh Bajaj All slides in this presentation.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Chapter 5 Decisions. Assignments  Written exercises pp 217 – 220 R5.1, R5.3, R5.5, R5.6, R5.9 – R5.15, R5.17, R R5.1, R5.3, R5.5, R5.6, R5.9 –
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. if (amount
Decisions CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 5, Horstmann*
Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester,
Basic Of Computer Science
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Chapter 3:Decision Structures.  3.1 The if Statement  3.2 The if-else Statement  3.3 The if-else-if Statement  3.4 Nested if Statements  3.5 Logical.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 5: Decisions 1 Chapter 5 Decisions.
Fall 2006Slides adapted from Java Concepts companion slides1 Decisions Advanced Programming ICOM 4015 Lecture 5 Reading: Java Concepts Chapter 6.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
1 2. Program Construction in Java. 2.4 Selection (decisions)
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
If Statement if (amount
Chapter 4 Control Structures I. Chapter Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate.
Week 7 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
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.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Week 7 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Decisions Bush decision making.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
Decision Statements, Short- Circuit Evaluation, Errors.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Control Statements: Part1  if, if…else, switch 1.
A First Book of C++ Chapter 4 Selection.
Java Programming Fifth Edition
Chapter Goals To implement decisions using if statements
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Chapter 5/6 Decisions.
Control Structure Chapter 3.
Chapter 5 – Decisions Big Java by Cay Horstmann
Boolean Expressions to Make Comparisons
Chapter 6 - Decisions.
Chapter 5 – Decisions Big Java by Cay Horstmann
Control Structure.
Presentation transcript:

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

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 Comparing Strings - II Case insensitive test ("Y" or "y") if ( input.equalsIgnoreCase("Y") )

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 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 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 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 Answers  (a) 0;  (b) 1;  (c) an exception is thrown

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 Answers Syntactically incorrect: e, g, h. Logically questionable: a, d, f

12 do we need the else?

13 no else statement

14 File EarthquakeTester.java

15 File Earthquake.java

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 Multiple Alternatives: Nested Branches Branch inside another branch if (condition1) { if (condition1a) statement1a; else statement1b; } else statement2;

Math 130 Decisions III Friday, Sept 14, 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

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 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 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 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 Using Boolean Expressions: The boolean Type George Boole ( ): pioneer in the study of logic value of expression amount < 1000 is true or false. boolean type: one of these 2 truth values

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 Predicate Methods II Useful predicate methods in Character class: isDigit isLetter isUpperCase isLowerCase if (Character.isUpperCase(ch))...

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

28 Truth Tables AND, OR, NOT

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

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

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

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 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 Answers When x is zero if (!Character.isDigit(ch))...

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