Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value.

Slides:



Advertisements
Similar presentations
Fundamental Programming Structures in Java: Control Flow, Arrays and Vectors.
Advertisements

1 Chapter Five Selection and Repetition. 2 Objectives How to make decisions using the if statement How to make decisions using the if-else statement How.
Chapter 6 Horstmann Programs that make decisions: the IF command.
Chapter 4 - Control Structures: Part 1 Outline 4.4Control Structures 4.5The if Selection Structure 4.6The if/else Selection Structure 4.7The while Repetition.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
C++ for Engineers and Scientists Third Edition
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Flow of Control Java Programming Mrs. C. Furman January 5, 2009.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
COMP Flow of Control: Branching 2 Yi Hong May 19, 2015.
Computer Science Selection Structures.
Chapter 3 Making Decisions
Object-Oriented Programming Using C++ Third Edition Chapter 3 Making Decisions.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Java Programming, Second Edition Chapter Five Input and Selection.
Visual C# 2005 Decision Structures. Visual C# Objectives Understand decision making Learn how to make decisions using the if statement Learn how.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Making Decisions. Understanding Logic-Planning Tools and Decision Making Pseudocode – A tool that helps programmers plan a program’s logic.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
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.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
Chapter 4 Introduction to Control Statements Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else Statements Section 4.
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.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
© The McGraw-Hill Companies, 2006 Chapter 2 Selection.
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.
Primitive data Week 3. Lecture outcomes Primitive data – integer – double – string – char – Float – Long – boolean Declaration Initialisation Assignments.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
PEG200/Saidatul Rahah 1.  Selection Criteria › if..else statement › relational operators › logical operators  The if-then-else Statement  Nested if.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
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.
Catie Welsh February 7,  Grades ◦ Lab 2, Project 1 Grades are now on Blackboard 2.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 5 Making Decisions.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Control Statements: Part1  if, if…else, switch 1.
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.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 4 Making Decisions.
Introduction to Control Statements IT108 George Mason University.
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
Chapter 4: Control Structures I
Java Programming Fifth Edition
More on the Selection Structure
Basics programming concepts-2
Chapter 4: Control Structures I
Selections Java.
Introduction to programming in java
EGR 2261 Unit 4 Control Structures I: Selection
SELECTION STATEMENTS (1)
Chapter 4: Control Structures I
Conditions and Ifs BIS1523 – Lecture 8.
SELECTION STATEMENTS (2)
Programming 2 Decision-Making.
Control Structure Chapter 3.
Lecture Notes – Week 2 Lecture-2
Boolean Expressions to Make Comparisons
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Presentation transcript:

Chapter 5– Making Decisions Dr. Jim Burns

In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value of someVariable is 10”);

if(someVariable==10)… The if(…) statement evaluates to true when the value of someVariable is 10 and to false when the value of someVariable is not 10 The System.out.println(..) only executes when the if(..) evaluates to true

In if(..) statements the Boolean expression must appear within parentheses The statement ends after the action to be taken if the Boolean expression is true is declared Then the semicolon appears

Irregardless of whether the Boolean expression is true or false, execution will continue with the next statement The System.out.println() statement executes only if the statement is true

The Result of every if(…) Every if(..) produced a Boolean result…either true or false

Single-alternative if(..) if(someVariable==10) System.out.println(“The value of someVariable is 10”); Only one action is performed based on the result of the Boolean expression

Dual-alternative if(..) Requires the use of the else keyword if(someVariable==10) System.out.println(“The value of someVariable is 10”); else System.out.println(“No, it’s not”); System.out.println(“No, it’s not”);

Nested IF’s If(itemsSold > 3) if(totalValue > 1000) bonus = 50; else bonus = 25; else bonus = 10;

Using Multiple statements in an if or if…else structure Must use braces to designate blocks

If(hoursWorked > 40) If(hoursWorked > 40){ regularPay = 40 * rate; regularPay = 40 * rate; overtimePay = (hoursWorked – 40) * 1.5 * rate overtimePay = (hoursWorked – 40) * 1.5 * rate System.out.println(“Regular pay is “ + regularPay); System.out.println(“Regular pay is “ + regularPay); System.out.println(“Overtime pay is “ + overtimePay); System.out.println(“Overtime pay is “ + overtimePay);}

import javax.swing.JOptionPane; public class Payroll { public static void main(String[] args) public static void main(String[] args) { String hoursString; String hoursString; double rate = 20.00; double rate = 20.00; double hoursWorked; double hoursWorked; double regularPay; double regularPay; double overtimePay; double overtimePay; hoursString = JOptionPane.showInputDialog(null, hoursString = JOptionPane.showInputDialog(null, "How many hours did you work this week?"); "How many hours did you work this week?"); hoursWorked = Double.parseDouble(hoursString); hoursWorked = Double.parseDouble(hoursString); if(hoursWorked > 40) if(hoursWorked > 40) { regularPay = 40 * rate; regularPay = 40 * rate; overtimePay = (hoursWorked - 40) * 1.5 * rate; overtimePay = (hoursWorked - 40) * 1.5 * rate; } else else { regularPay = hoursWorked * rate; regularPay = hoursWorked * rate; overtimePay = 0.0; overtimePay = 0.0; } JOptionPane.showMessageDialog(null, "Regular pay is " + JOptionPane.showMessageDialog(null, "Regular pay is " + regularPay + "\nOvertime pay is " + overtimePay); regularPay + "\nOvertime pay is " + overtimePay); System.exit(0); System.exit(0); }}

if(hoursWorked > 40) if(hoursWorked > 40) { regularPay = 40 * rate; regularPay = 40 * rate; overtimePay = (hoursWorked - 40) * 1.5 * rate; overtimePay = (hoursWorked - 40) * 1.5 * rate; } else else { regularPay = hoursWorked * rate; regularPay = hoursWorked * rate; overtimePay = 0.0; overtimePay = 0.0; }

if(…) cannot ask.. “What number did the user enter?” INSTEAD… “Did the user enter a 1?” “Did the user enter a 2?” “Did the user enter a 3?”

Observe the use of else If(itemsSold > 3) if(totalValue > 1000) bonus = 50; else bonus = 25; else bonus = 10;

Using logical AND and OR statements Rather than nested if’s, can AND two or more Boolean expressions together –The result is true only if all Boolean expressions are true Bonus = 0; If(itemsSold > 3 && totalValue > 1000) bonus = 50;

The code above works like… Bonus = 0; If(itemsSold > 3) if(totalValue > 1000) bonus = 50;

So why use the && operator?? It makes your code more concise, less error-prone, and easier to understand Note that when you use the && operator, you must include a complete Boolean expression on each side of the &&

bonus = 0; If(itemsSold > 100) bonus = 200; else if(totalValue > 3000) bonus = 200; Accomplishes the same as….. bonus = 0; If(itemsSold > 100 || totalValue > 3000) bonus = 200;

Avoiding Common errors when making decisions Using the assignment operator instead of the comparison operator when testing for equality Inserting a semicolon after the Boolean expression in an if statement Failing to block a set of statements with curly braces when several statements depend on the if or the else statement

Still more common errors… Failing to include a complete Boolean expression on each side of an && or || operator in an if statement Performing a range check incorrectly or inefficiently Using the wrong operator with AND and OR

Performing accurate and efficient range checks A range check is a series of if statements that determine whether a value falls within a specified range

Incorrect range check code If(saleAmount >= 1000) commissionRate =.08; If(saleAmount >= 500) commissionRate =.06; If(saleAmount <= 499) commissionRate =.05;

Correct range check code…but inefficient If(saleAmount >= 1000) commissionRate =.08; else if(saleAmount >= 500) commissionRate =.06; else if(saleAmount <= 499) commissionRate = 0.05;.. else commissionRate = 0.05;

Using AND and OR appropriately The boss might say “Print an error message when an employee’s hourly rate is under $5.65 and when an employee’s hourly pay rate is over $60” If(payRate 60) System.out.println(“Error in pay rate”); What is wrong with this and how do you fix the problem?

ANDing two Boolean expressions together Boolean Expression 1 Boolean Expression 2 Result of AND ing them true false truefalse

Both of the Boolean expressions have to be true in order for the result of ANDing them to return a value of true

ORing two Boolean expressions together Boolean Expression 1 Boolean Expression 2 Result of OR ing them true falsetrue falsetrue false

When ORing, if either Boolean expression is true, the result of ORing is true. It’s only when both of the Boolean expressions are false that the result of ORing is false

Using the switch statement if(year == 1) System.out.println(“Freshman”); else if(year == 2) System.out.println(“Sophmore”); else if(year == 3) System.out.println(“Junior”); else if(year == 4) System.out.println(“Senior”); else System.out.println(“Invalid year”); Instead use the switch statement..

Int year; //get year value from user input or database Switch(year) { case 1: System.out.println(“Freshman”); break; case 2: System.out.println(“Sophomore”); break; case 3: System.out.println(“Junior”); break; case 4: System.out.println(“Senior”); break; default: System.out.println(“Invalid year”); }

Int year; //get year value from user input or database Switch(year) { case 1: System.out.println(“Freshman”); case 2: System.out.println(“Sophomore”); case 3: System.out.println(“Junior”); case 4: System.out.println(“Senior”); default: System.out.println(“Invalid year”); }

Int year; //get year value from user input or database Switch(year) { case 1: System.out.println(“Freshman”); Break; case 2: System.out.println(“Sophomore”); Break; case 3: System.out.println(“Junior”); Break; case 4: System.out.println(“Senior”); Break; default: System.out.println(“Invalid year”);

In the code above…. The switch structure begins by evaluating the year variable in the switch statement If year is equal to the first case value, which is one, “Freshman” is printed The break statements bypass the rest of the switch structure and execution continues with the statement following the closing curly brace of the switch structure

switch() What is the data type of the argument of a switch() statement? Int, char, short and byte Does a semicolon follow a switch statement? What delimiter follows each case statement? Are the break statements necessary for the code to work right?

int department; String supervisor; // Statement to get department value Switch (department) { case 1: case 2: case 3: supervisor = “Jones”; Break; case 4: supervisor = “Staples”;

break; case 5; supervisor = “Tejano”; break;default: System.out.println(“Invalid department code”); }

Using the conditional AND NOT Operators

Consider the following code… If(a < b) smallerNum = a; else smallerNum = b; smallerNum = (a < b) ? A : b; The conditional operator uses the ? and the : to separate three expressions; the first expression must be a Boolean expression

Using the NOT Operator You use the NOT operator which is written as the exclamation point (!), to negate the result of any Boolean expression If (age <= 25) premium = 200; else premium = 125; If(!(age <= 25)) premium = 125; else premium = 200;

Understanding precedence PrecedenceOperator(s)Symbols HighestLogical NOT ! IntermediateMultiplication, division, modulus * / % Addition, subtraction + - Relational> = <= Equality == != Logical AND && Logical OR || Conditional ? : lowestAssignment =

Precedence Order of precedence agrees with common algebraic practice Notice that the and && operator is always evaluated before the or || operator

Example Consider an auto insurance sys that determines the amount of premium to charge Additional premium is charged to a driver who meets both of the following criteria: –Has more than two traffic tickets or is under 25 years old –Is male Consider a 30 year old female driver with three traffic tickets

Code implementations // assigns extra premiums incorrectly if(trafficTickets > 2 || age < 25 && gender == ‘M’) extraPremium = 200; // assigns extra premiums correctly If((trafficTickets > 2 || age < 25) && gender == ‘M’) extraPremium = 200; Remember, do what is inside () first

import javax.swing.JOptionPane; public class Payroll { public static void main(String[] args) { String hoursString; double rate = 20.00; double hoursWorked; double regularPay; double overtimePay; hoursString = JOptionPane.showInputDialog(null, "How many hours did you work this week?"); hoursWorked =

Double.parseDouble(hoursString); if(hoursWorked > 40) { regularPay = 40 * rate; overtimePay = (hoursWorked - 40) * 1.5 * rate; } else { regularPay = hoursWorked * rate; overtimePay = 0.0; } JOptionPane.showMessageDialog(null, "Regular pay is " + regularPay + "\nOvertime pay is " + overtimePay); System.exit(0); }