Chapter 5/6 Decisions.

Slides:



Advertisements
Similar presentations
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
Advertisements

Control Structures Control structures are used to manage the order in which statements in computer programs will be executed Three different approaches.
Math 130 Decisions II Wed, Sept 12, 2007 Notes: ref. C. Horstmann, Java Concepts.
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.
Chapter 6 Horstmann Programs that make decisions: the IF command.
Chapter 5  Decisions 1 Chapter 5 Decisions. Chapter 5  Decisions 2 Chapter Goals  To be able to implement decisions using if statements  To understand.
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
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Conditional Statements Control Structures.
Chapter 5 – Decisions Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Logical Operators and Conditional statements
1 Selection Structures. 2 Making Decisions Sample assignment statements to figure worker pay with possible overtime PayAmount = Hours * Rate PayAmount.
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.
COM S 207 IF Statement Instructor: Ying Cai Department of Computer Science Iowa State University
Decision Structures and Boolean Logic
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 –
Chapter Goals To implement decisions using if statements
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
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,
Flow of Control Part 1: Selection
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 4 Decision.
©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.
1 Chapter 4: Basic Control Flow ► Chapter Goals  To be able to implement decisions using if statements  To understand statement blocks  To learn how.
If Statement if (amount
Week 7 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
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.
Week 7 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Decisions Bush decision making.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 5 - Decisions.
A First Book of C++ Chapter 4 Selection.
Chapter 3 Control Statements
Selection (also known as Branching) Jumail Bin Taliba by
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.
5.3 Multiple Alternatives (Part 1)
Chapter 4: Making Decisions.
Chapter 5 – Decisions.
Chapter 3 Edited by JJ Shepherd
EGR 2261 Unit 4 Control Structures I: Selection
Nested Branches Nested set of statements: Example: Federal Income Tax
The Selection Structure
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Topics The if Statement The if-else Statement Comparing Strings
Chapter 4: Making Decisions.
Topics The if Statement The if-else Statement Comparing Strings
DECISIONS.
Objectives After studying this chapter, you should be able to:
Summary Two basic concepts: variables and assignments Basic types:
Control Structure Chapter 3.
Chapter 5 – Decisions Big Java by Cay Horstmann
Chapter 2 Programming Basics.
Chapter 6 - Decisions.
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Chapter 5 – Decisions Big Java by Cay Horstmann
Presentation transcript:

Chapter 5/6 Decisions

Dagens tekst Flow control : if (..) then ... else ... Loops : gentagelser: ...

Dagens tekst Flow control : if (..) then ... else ... Loops : gentagelser: ... MEN MEGET HURTIGT FORDI opgaver giver mest læring derfor mere tid til jer bagefter :-) vi må videre ...

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

The if Statement The if statement lets a program carry out different actions depending on a condition if (amount <= balance) balance = balance - amount; Continued…

The if Statement Figure 1: Flowchart for an if statement

The if/else Statement if (amount <= balance) balance = balance - amount; else balance = balance - OVERDRAFT_PENALTY; Continued…

The if/else Statement Figure 2: Flowchart for an if/else statement

Statement Types Simple statement Compound statement Also while, for, etc. (loop statements–see LOC) balance = balance - amount; if (balance >= amount) balance = balance - amount; Continued…

Statement Types Block statement (!) {     double newBalance = balance - amount;     balance = newBalance; }

Syntax 6.1: The if Statement  if(condition)    statement if (condition)    statement1 else    statement2 Example:  if (amount <= balance) balance = balance - amount; if (amount <= balance) balance = balance - amount; else balance = balance - OVERDRAFT_PENALTY; Purpose: To execute a statement when a condition is true or false

Syntax 6.2: Block Statement  {    statement1    statement2    . . . } Example:  { double newBalance = balance - amount; balance = newBalance; } Purpose: To group several statements together to form a single statement

Self-Check Why did we use the condition amount <= balance and not amount < balance in the example for the if/else statement? What is logically wrong with the statement and how do you fix it? if (amount <= balance) newBalance = balance - amount; balance = newBalance;

Answers If the withdrawal amount equals the balance, the result should be a zero balance and no penalty Only the first assignment statement is part of the if statement. Use braces to group both assignment statements into a block statement

Comparing Values: Relational Operators Relational operators compare values The == denotes equality testing !!!!!!!!! Not equal ≠ !+ Equal = == Less than or equal ≤ <= Less than < Greater than or equal ≥ >= Greater than > Description Math Notation Java a = 5; // Assign 5 to a if (a == 5) . . . // Test whether a equals 5

Comparing Floating-Point Numbers Consider this code: It prints:   double r = Math.sqrt(2); double d = r * r -2; if (d == 0) System.out.println("sqrt(2)squared minus 2 is 0"); else System.out.println("sqrt(2)squared minus 2 is not 0 but " + d); sqrt(2)squared minus 2 is not 0 but 4.440892098500626E-16

Comparing 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| ≤ ε ε is a small number such as 10-14 final double EPSILON = 1E-14; if (Math.abs(x - y) <= EPSILON) // x is approximately equal to y

Comparing Strings Don't use == for strings! Use equals method: == tests identity, equals tests equal contents Case insensitive test ("Y" or "y") if (input == "Y") // WRONG!!! if (input.equals("Y")) if (input.equalsIgnoreCase("Y")) Continued…

Comparing Strings 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" Jan & Jens: danske,græske,kyrilliske bogstaver ? well ... engelsk sproget bog

Lexicographic Comparison Figure 3: Lexicographic Comparison

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

Object Comparison Figure 4: Comparing Object References

Self Check What is the value of s.length() if s is the empty string ""? the string " " containing a space? null?

Self-Check 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 == "1" a == null a.equals("") a == b a == x x == y x - y == null x.equals(y)

Answers (a) 0; (b) 1; (c) an exception is thrown Syntactically incorrect: e, g, h. Logically questionable: a, d, f men hurtigt videre :-)

Multiple Alternatives: Sequences of Comparisons The first matching condition is executed Order matters "; . . . Don't omit else if (richter >= 8.0)    r = "Most structures fall"; if (richter >= 7.0) // omitted else--ERROR    r = "Many buildings destroyed if (condition1)    statement1; else if (condition2)    statement2; . . . else    statement4; 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 . . . Continued…

Multiple Alternatives: Sequences of Comparisons Don't omit else if (richter >= 8.0)    r = "Most structures fall"; if (richter >= 7.0) // omitted else--ERROR    r = "Many buildings destroyed”; if (richter >= 2.0) // omitted else--ERROR    r = "shake it “;

Answers Yes, if you also reverse the comparisons: if (richter < 3.5) r = "Generally not felt by people"; else if (richter < 4.5) r = "Felt by many people, no destruction"; else if (richter < 6.0) r = "Damage to poorly constructed buildings"; . . .

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

Tax Schedule If your filing status is married If your filing status is single 31% Amount over $86,500 Amount over $51,900 28% Amount over $35,800, up to $86,500 Amount over $21,451, up to $51,900 15% $0 … $35,800 $0 … $21,450 Percentage Tax Bracket

Nested Branches 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 We say that the income test is nested inside the test for filing status Continued…

Nested Branches Figure 5: Income Tax Computation Using 1992 Schedule

Self Check Some people object to higher tax rates for higher incomes, claiming that you might end up with less money after taxes when you get a raise for working hard. What is the flaw in this argument?

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

Using Boolean Expressions: The boolean Type

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

Using Boolean Expressions: Predicate Method Useful predicate methods in Character class: Useful predicate methods in Scanner class: hasNextInt() and hasNextDouble() isDigit isLetter isUpperCase isLowerCase if (Character.isUpperCase(ch)) . . . if (in.hasNextInt()) n = in.nextInt();

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

&& and || Operators Figure 6: Flowcharts for && and || Combinations

Truth Tables False Any True A&&B B A False True Any A||B B A True

Using Boolean Variables Also called flag It is considered gauche to write a test such as Just use the simpler test if (married == true) . . . // Don't if (married) . . .

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