Chapter 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

Math 130 Decisions II Wed, Sept 12, 2007 Notes: ref. C. Horstmann, Java Concepts.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Chapter 5 Selection Statements. Topics Controlling program flow selection –if –switch Boolean expressions –boolean primitive type –comparison operators.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
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 4: Mathematical Operators New York University.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
If Statement if (amount
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Chapter 5 – Decisions Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
Logical Operators and Conditional statements
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
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 6 - Decisions. Characters char char primitive data type primitive data type stores a single character stores a single character operations (same.
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,
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
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.
Fall 2006Slides adapted from Java Concepts companion slides1 Decisions Advanced Programming ICOM 4015 Lecture 5 Reading: Java Concepts Chapter 6.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
If Statement if (amount
Chapter Making Decisions 4. Relational Operators 4.1.
Week 7 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
ICT Introduction to Programming Chapter 4 – Control Structures I.
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.
Decisions Bush decision making.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
Java Programming Fifth Edition
COMP 14 Introduction to Programming
Selection (also known as Branching) Jumail Bin Taliba by
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 4: Making Decisions.
Chapter 3 Edited by JJ Shepherd
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Branching Statements
Week 4 - Monday CS 121.
The Selection Structure
Chapter 4: Making Decisions.
Chapter 5/6 Decisions.
Control Structures – Selection
Java Programming Control Structures Part 1
Control Structure Chapter 3.
Chapter 5 – Decisions Big Java by Cay Horstmann
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Just Enough Java 17-May-19.
Announcements Program 1 due noon Lab 1 due noon
Control Structure.
Selection Statements August 22, 2019 ICS102: The course.
Chapter 13 Control Structures
Presentation transcript:

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

Decisions So far, our examples haven’t made any decisions The same code gets executed no matter what Assignment 1 Path BankAccount This is called sequential execution Is this how real applications work?

Decisions The real world requires decisions 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 The answers to these decision require different actions Introduces the need for control statements

If statements Conditional statements are represented with if-then-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”);

If Statements: Syntax if (<boolean expression>) { <then block> } else { <else block>

Example What decision should withdraw() make? withdraw() method we implemented allowed user to withdraw as much money as they wanted Is this realistic? What decision should withdraw() make? What should the decision be based on?

Example public void withdraw(double amount){ if (amount <= balance) balance -= amount; }

Example Most banks also charge an overdraft penalty, how would we go about changing our example to implement this?

Statements The decision we made only resulted in one instruction whichever way we took Most decisions lead to a sequence of instructions (multiple statements). In order to show that the entire sequence of instructions belong to the then-block (or else-block), we group them with curly braces{ } A sequence of instructions surrounded by curly braces is called a block

Example if (amount <= balance) { System.out.println(“Legal Withdrawal”); balance = balance – amount; } else balance = balance – OVERDRAFT_PENALTY;

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

If Statements 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 Helpful for adding temporary output to check if a branch is executed Makes nested if-else statements easier to read

If Statements: Syntax if(condition) statement else  statement2 statement must be a statement - simple, compound, or block

Style Use indentation to indicate nesting levels public class BankAccount { | … | public void withdraw() | { | | if (amount <= balance) | | { | | | balance -= amount; | | } | } }

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

Die Example // Test for doubles if ( roll1 == roll2 ) System.out.println( "Doubles" ); // rest of program

Die Example roll1 == roll2 true System.out.println( “doubles!” ); false ... continue with rest of program

Die Example // Test for doubles if ( roll1 == roll2 ) System.out.println( "Doubles" ); else System.out.println( "Sorry, no doubles" ); // rest of program

Die Example roll1 == roll2 true System.out.println( “doubles!” ); false System.out.println( “sorry ...” ); ... continue with rest of program

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

Booleans boolean is a primitive data type that holds one of two values true false Any time a decision needs to be made, we make that decision using a boolean expression, which evaluates to a boolean value Note: a mathematical expression returns a numerical value

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

Boolean Expressions Boolean expressions are just like mathematical expressions, but they return true or false (not int, double, etc) Examples: 3 * 8 <= 5 * 5 6 % 4 > 0 testScore < 80 testScore * 2 > 350

If Statements When the computer reaches an if statement, it first evaluates the boolean expression If that expression is true, the <then block> is executed Otherwise, the <else block> is executed An if statement is called a branching statement because it branches to a block of code

Comparisons Comparing whole numbers is trivial int a = 5; if (a == 5){ System.out.println(“Wow this is easy!”); } else { System.out.println(“Java really sucks”); }

Comparisons Comparing real numbers is more difficult because we have to take 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

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

Comparisons To avoid roundoff errors, don't use == or != to compare floating-point numbers 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

Comparisons We can do comparisons with characters as well They work according to ASCII values: char choice = 'Q'; if (choice < 'Z') System.out.println("valid"); else System.out.println("invalid"); What is the output? Explain basics of an if statement here. Point out the conditional expression: choice < 'Z' Explain that Java stores characters as int values and that is why we can compare, add, subtract, etc. Useful for sorting.

Side Note: Characters Remember that we said a char is one letter, digit, or symbol that the computer thinks of as a number. We can cast chars to int and vice versa Examples: (int) 'D' -> 68 (char) 106 -> 'j' (char) ('D' + 1) -> 'E'

Comparisons Boolean operators can be used on objects, but do they mean the same thing? They probably don’t do what you expect… Primitive types vs. reference types (objects) To test two Strings, use equals() method

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

String Comparisons String s1 = "Robby", s2; s2 = s1; :String R s1 o b 0 1 2 3 4 s2

String Comparisons What is the result of: s1 == s2 Why? :String R s1 o b y 0 1 2 3 4 s2 Why?

String Comparisons String s1 = "Robby", s2; s2 = "Robby"; :String R s1 0 1 2 3 4 The first occurrence of "Robby" results in a new object being created. But, additional occurrences of "Robby" will not create new objects and instead the compiler "remembers" the symbol and uses the existing address for the new variable assignment. s2

String Comparisons What is the result of: str1 == str2 Why? :String R b y 0 1 2 3 4 str2 Why?

String Comparisons String s1 = "Robby", s2; s2 = new String( s1 ); 0 1 2 3 4 :String R o b y 0 1 2 3 4 s2

String Comparisons What is the result of: s1 == s2 Why? :String b y 0 1 2 3 4 :String R s2 o b y 0 1 2 3 4 Why?

String Comparisons What is the result of: s1.equals(s2); Why? :String b y 0 1 2 3 4 :String R s2 o b y 0 1 2 3 4 Why?

String Comparisons equalsIgnoreCase can be used to compare strings while ignoring case Case insensitive test ("Y" or "y") if (input.equalsIgnoreCase("Y")) string1.equalsIgnoreCase(string2) // returns boolean compareTo returns a number that tells which string comes before the other in the dictionary 0 indicates that the strings are the same

String Comparisons Returns < 0 if string1 comes first string1.compareTo(string2) Returns < 0 if string1 comes first Returns 0 if they are equal Returns > 1 if string2 comes first Example: "car" comes before "cargo" All uppercase letters come before lowercase: "Hello" comes before "car"

Comparisons == tests for identity, equals() for identical content 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 is false box1.equals(box3)is true box1 == box2 is true Note: equals() must be defined for the class for this to work

Null 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? null is a Java reserved word to designate that no object has been set for that variable

Null Can be used in tests: Use ==, not equals, to test for null 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 ""

Multiple Alternatives if (score >= 90) System.out.println("Great!"); else if (score >= 80) System.out.println("Good"); else if (testScore >= 70) System.out.println("OK"); else if (testScore >= 60) System.out.println("Passing"); else if (testScore >= 50) System.out.println("Hmm..."); else if (testScore >= 0) System.out.println("Study!"); else System.out.println("Invalid Score");

Multiple alternatives First condition that is true is the ONLY statement executed Therefore, order matters: if (testScore >= 90) System.out.println(“Great!”); else if (testScore >= 80) System.out.println(“Good”); else if (testScore >= 70) System.out.println(“OK”);

Multiple Alternatives Wrong order here causes problems! if (testScore >= 0) System.out.println(“Study!”); else if (testScore >= 50) System.out.println(“Hmm...”); else if (testScore >= 60) System.out.println(“Passing”);

Multiple Alternatives if (testScore >= 90) System.out.println(“Great!”); if (testScore >= 70) System.out.println(“OK”); if (testScore >= 50) System.out.println(“Hmm...”); These aren't exclusive statements anymore Else matters!!!

Switch Statements switch ( <variable name> ){ <case label 1>: <case body 1> ... <case label n>: <case body n> } Can only be used on integers, characters, or enumerated constants Good for testing multiple values for one expression

Switch Statements

Switch Statements 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.

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

Nested Decisions These blocks can also have another if statement then and else blocks can contain as many statements as needed These blocks can also have another if statement An if statement inside of another if statement is called a nested-if statement

Nested Decisions 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”);

Tax Schedule Example

Tax Schedule Example Compute taxes due, given filing status and income figure: branch on the filing status 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

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

else { if (income <= MARRIED_BRACKET1){ tax = RATE1 * income; } else if (income <= MARRIED_BRACKET2) { tax = RATE1 * MARRIED_BRACKET1 + RATE2 * (income - MARRIED_BRACKET1); } else { + RATE2 * (MARRIED_BRACKET2 - MARRIED_BRACKET1) + RATE3 * (income - MARRIED_BRACKET2); }

Dangling Else There is a good reason we always use curly braces in our programs 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”);

Dangling Else Which if statement does the else apply to? Always the closest unclosed if if (testScore >=60) if(testScore <= 80) System.out.println(“You are in safe range”); else System.out.println(“You may be in trouble”);

Using Boolean Expressions Recall that the last primitive that we really haven't said much about is the boolean data type double temp = 100; boolean isHot = temp > 60; System.out.println(“Is it hot? Ans: ” + isHot);

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

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

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 in = new Scanner(System.in); int score; System.out.println(“Enter Score”); if(in.hasNextInt()) score = in.nextInt()

Boolean Operators What if we want one expression to test multiple conditions? Example: Does a student have a score above 50 and below 75? Need boolean operators

Boolean Operators Can use a logical operator to test simultaneously && AND true if both are true, false otherwise || OR true if either is true, false otherwise ! NOT true of the expression is false, false if it is true

Boolean Operators

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

Many ways to write one expression: if (age < 0){ System.out.print(“valid”); } else { System.out.print(“invalid”); } ------------------------------------- if (!(age >= 0)){ ---------------------------------- if (age >= 0){

Order of Operations Like before, boolean operators are evaluated left to right Example: Suppose y has the value 0 x / y > z || y == 0 // Run time error, divide by // zero y == 0 || x / y > z // Legal

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

Example In math, we represent the range of x as How do we represent this as a boolean expression? (Be careful)

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

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