Control Stuctures Module 4 Copyright © 2006. Copyright © 2006. Slide #2 Decision Structures Chapter Objectives To understand: how to write boolean expressions.

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming
Advertisements

Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
1 Fall 2007ACS-1903 Chapter 3 Decision Structures The if Statement The if-else Statement The if-else-if Statement Nested if Statements Logical Operators.
Chapter 5 Selection Statements. Topics Controlling program flow selection –if –switch Boolean expressions –boolean primitive type –comparison operators.
1 Fall 2008ACS-1903 Chapter 3 Decision Structures The if Statement The if-else Statement The if-else-if Statement Nested if Statements Logical Operators.
Flow of Control (1) : Logic Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
The if Statement The code in methods executes sequentially.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Logical Operators and Conditional statements
Chapter 3: Decision Structures Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis.
The switch Statement, DecimalFormat, and Introduction to Looping
© 2012 Pearson Education, Inc. All rights reserved. Chapter 3: Decision Structures Starting Out with Java: From Control Structures through Data Structures.
Chapter 3 Decision Structures 1. Contents 1.The if Statement 2.The if-else Statement 3.The if-else-if Statement 4.Nested if Statement 5.Logical Operators.
Lecture 3 Decision Structures. 4-2 Topics – The if Statement – The if - else Statement – The PayRoll class – Nested if Statements – The if - else - if.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 4 Decision Structures and Boolean Logic.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Decision Structures and Boolean Logic
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 3 Decision Structures Starting Out with Java: From Control Structures through Objects.
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
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
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.
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA Prof. Dr. Paulo Brasko Ferreira Fall 2013.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Chapter 3: Decision Structures
CHAPTER 3 Decision Structures Copyright © 2016 Pearson Education, Inc., Hoboken NJ.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: From Control Structures through Objects Third Edition.
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.
Control statements Mostafa Abdallah
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC INTRO TO COMPUTING - PROGRAMMING If Statement.
Starting Out With Java 5 (Control Structures to Objects) Chapter 3 By Tony Gaddis Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
Decision Statements, Short- Circuit Evaluation, Errors.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CHAPTER 3 Decision Structures Copyright © 2016 Pearson Education, Ltd.
Lecture 3 Selection Statements
INTERMEDIATE PROGRAMMING USING JAVA
Chapter 3 Control Statements
CS0007: Introduction to Computer Programming
Chapter 3: Decision Structures by Tony Gaddis and Godfrey Muganda
Chapter 3: Decision Structures
Selections Java.
The switch Statement, and Introduction to Looping
Lecture 3- Decision Structures
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Topics The if Statement The if-else Statement Comparing Strings
Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz
Chapter 3: Decision Structures
if-else-if Statements
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Chapter 3: Decision Structures
Topics The if Statement The if-else Statement Comparing Strings
Starting Out With Java 5 (Control Structures to Objects) Chapter 3
Chapter 3:Decision Structures
The System.exit() Method
CprE 185: Intro to Problem Solving (using C)
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Presentation transcript:

Control Stuctures Module 4 Copyright © 2006

Copyright © Slide #2 Decision Structures Chapter Objectives To understand: how to write boolean expressions how to write: if statements, if-else statements, and if-else-if statements how to write nested if statements the concept of a flag variable how to compare String objects using: equals(), compareTo(), equalsIgnoreCase(), and compareToIgnoreCase()

Copyright © Slide #3 Chapter Objectives To understand: how the scope of a variables declared inside a set of curly braces, such as those belonging to an if statement the conditional operator switch statements how to format numbers using the standard DecimalFormat class the concept of algorithm decomposition and how a lengthy or complex method can be broken into several methods that each perform a related task the role of private methods

Copyright © Slide #4 Chapter Topics Chapter 4 discusses the following main topics: The if Statement The if-else Statement The Payroll Class The if-else-if Statement Nested if Statements Logical Operators Comparing String Objects

Copyright © Slide #5 Chapter Topics Chapter 4 discusses the following main topics: More about Variable Declaration and Scope The Conditional Operator The switch Statement The DecimalFormat Class The SalesCommission Class

Copyright © Slide #6 The if Statement The code in methods executes sequentially. The if statement allows the programmer to make decisions on whether a section of code executes or not. The if statement uses a boolean expression as an argument to decide if the next statement or block of statements executes. if(boolean expression is true) execute next statement.

Copyright © Slide #7 Flowcharts If statements can be modeled as a flow chart. Wear a coat. Yes Is it cold outside? if (coldOutside) wearCoat();

Copyright © Slide #8 Flowcharts A block if statement may be modeled as: Wear a coat. Yes Is it cold outside? Wear a hat. Wear gloves. if (coldOutside){ wearCoat(); wearHat(); wearGloves(); } Note the use of curly braces to block several statements together.

Copyright © Slide #9 Relational Operators In most cases, the boolean expression, used by the if statement, uses relational operators. Relational OperatorMeaning > is greater than < is less than >= is greater than or equal to <= is less than or equal to == is equal to != is not equal to

Copyright © Slide #10 Boolean Expressions A boolean expression is any variable or calculation that results in a true or false condition. ExpressionMeaning x > y Is x greater than y? x < y Is x less than y? x >= y Is x greater than or equal to y? x <= y Is x less than or equal to y. x == y Is x equal to y? x != y Is x not equal to y?

Copyright © Slide #11 If Statements and Boolean Expressions if (x > y) System.out.println(“X is greater than Y”); if(x == y) System.out.println(“X is equal to Y”); if(x != y){ System.out.println(“X is not equal to Y”); x = y; System.out.println(“However, now it is.”); } Example: AverageScore.javaAverageScore.java

Copyright © Slide #12 Programming Style and if Statements If statements can span more than one line; however, they are still one statement. if(average > 95) System.out.println(“That’s a great score!”); is functionally equivalent to if(average > 95) System.out.println(“That’s a great score!”);

Copyright © Slide #13 Programming Style and if Statements Rules of thumb: The conditionally executed statement should be on the line after the if condition. The conditionally executed statement should be indented one level from the if condition. If an if statement does not have the block curly braces, it is ended by the first semicolon encountered after the if condition. if(expression) statement; No semicolon here. Semicolon ends statement here.

Copyright © Slide #14 Block if Statements Conditionally executed statements can be grouped into a block by using curly braces {} to enclose them. If curly braces are used to group conditionally executed statements, the if statement is ended by the closing curly brace. if(expression){ statement1; statement2; } Curly brace ends the statement.

Copyright © Slide #15 Block if Statements Remember that if the curly braces are not used, then only the next statement after the if condition will be executed conditionally. if(expression) statement1; statement2; statement3; Only this statement is conditionally executed.

Copyright © Slide #16 Flags A flag is a boolean variable that monitors some condition in a program. When a condition is true, the flag is set to a true value. The flag can be tested to see if the condition has changed. if(average > 95) highScore = true; Later, this condition can be tested: if(highScore) System.out.println(“That’s a high score!);

Copyright © Slide #17 Comparing Characters Characters can be tested using the relational operators. Characters are stored in the computer using the unicode character format. Unicode is stored as a sixteen (16) bit number. Characters are ordinal, meaning they have an order in the unicode character set. Since characters are ordinal, they can be compared to each other. char c = ‘A’; if(c < ‘Z’) System.out.println(“A is less than Z);

Copyright © Slide #18 if-else Statements The if-else statement adds the ability to conditionally execute code based if the expression of the if statement is false. if(expression) statementOrBlockIfTrue; else statementOrBlockIfFalse; Example: Division.javaDivision.java

Copyright © Slide #19 if-else Statement Flowcharts Wear a coat. Yes Is it cold outside? Wear shorts. No

Copyright © Slide #20 The Payroll Class Payroll - hoursWorked : double - payRate : double + setHoursWorked(hours : double) : void + setPayRate(rate : double): void + getHoursWorked() : double + getPayRate() : double + getGrossPay() : double Example Files: Payroll.java GrossPay.java

Copyright © Slide #21 if-else-if Statements if-else-if statements can become very complex. Imagine the following decision set. if it is very cold, wear a heavy coat, else, if it is chilly, wear a light jacket, else, if it is windy wear a windbreaker, else, if it is hot, wear no jacket.

Copyright © Slide #22 if-else-if Statements if (expression) statement or block else if (expression) statement or block // Put as many else ifs as needed here else statement or block Care must be used since else statements match up with the immediately preceding unmatched if statement. Example: TestGrade.javaTestGrade.java Example: TestResults.javaTestResults.java

Copyright © Slide #23 if-else-if Flowchart

Copyright © Slide #24 Nested if Statements If an if statement appears inside of another if statement (single or block) it is called a nested if statement. The nested if is only executed if the if statement it is in results in a true condition. Nested if statements can get very complex, very quickly. Example: LoanQualifier.javaLoanQualifier.java

Copyright © Slide #25 Nested if Statement Flowcharts Wear a jacket. Yes Is it cold outside? Wear shorts. Is it snowing? Wear a parka. No Yes

Copyright © Slide #26 if-else Matching Curly brace use is not required if there is only one statement to be conditionally executed. However, sometimes curly braces can help make the program more readable. Additionally, proper indentation makes it much easier to match up else statements with their corresponding if statement.

Copyright © Slide #27 if-else Matching if (employed == 'y') { if (recentGrad == 'y') { System.out.println("You qualify for the special interest rate."); } else { System.out.println("You must be a recent college graduate to qualify."); } else { System.out.println("You must be employed to qualify."); } This else matches with this if. This else matches with this if.

Copyright © Slide #28 Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!) logical operator to reverse the truth of a boolean expression.

Copyright © Slide #29 Logical Operators OperatorMeaningEffect &&AND Connects two boolean expressions into one. Both expressions must be true for the overall expression to be true. ||OR Connects two boolean expressions into one. One or both expressions must be true for the overall expression to be true. It is only necessary for one to be true, and it does not matter which one. !NOT The ! operator reverses the truth of a boolean expression. If it is applied to an expression that is true, the operator returns false. If it is applied to an expression that is false, the operator returns true.

Copyright © Slide #30 The && Operator The logical AND operator (&&) takes two operands that must both be boolean expressions. The resulting combined expression is true iff (if and only if) both operands are true. Example: LogicalAnd.javaLogicalAnd.java Expression 1Expression 2Expression1 && Expression2 truefalse truefalse true

Copyright © Slide #31 The || Operator The logical OR operator (||) takes two operands that must both be boolean expressions. The resulting combined expression is false iff (if and only if) both operands are false. Example: LogicalOr.javaLogicalOr.java Expression 1Expression 2Expression1 || Expression2 truefalsetrue falsetrue false true

Copyright © Slide #32 The ! Operator The ! operator performs a logical NOT operation. If an expression is true, !expression will be false. if (!(temperature > 100)) System.out.println(“Below the maximum temperature."); If temperature > 100 evaluates to false, then the output statement will be run. Example: LogicalNot.javaLogicalNot.java Expression 1!Expression1 truefalse true

Copyright © Slide #33 Short Circuiting Logical AND and logical OR operations perform short-circuit evaluation of expressions. Logical AND will evaluate to false as soon as it sees that one of its operands is a false expression. Logical OR will evaluate to true as soon as it sees that one of its operands is a true expression.

Copyright © Slide #34 Order of Precedence The ! operator has a higher order of precedence than the && and || operators. The && and || operators have a lower precedence than relational operators like. Parenthesis can be used to force the precedence to be changed.

Copyright © Slide #35 Order of Precedence OperatorsDescription 1(unary negation) !Unary negation, logical NOT 2* / %Multiplication, Division, Modulus 3+ -Addition, Subtraction 4 = Less-than, Greater-than, Less-than or equal to, Greater-than or equal to 5== !=Is equal to, Is not equal to 6&&Logical AND 7||Logical NOT 8 = += -= *= /= %= Assignment and combined assignment operators.

Copyright © Slide #36 Comparing String Objects In most cases, you cannot use the relational operators to compare two String objects. Reference variables contain the address of the object they represent. Unless the references point to the same object, the relational operators will not return true. Example: BadStringCompare.javaBadStringCompare.java Example: GoodStringCompare.javaGoodStringCompare.java Example: StringCompareTo.javaStringCompareTo.java

Copyright © Slide #37 Ignoring Case in String Comparisons In the String class the equals and compareTo methods are case sensitive. In order to compare two String objects that might have different case, use: equalsIgnoreCase, or compareToIgnoreCase Example: SecretWord.javaSecretWord.java Example: CompareWithoutCase.javaCompareWithoutCase.java

Copyright © Slide #38 Variable Scope In Java, a local variable does not have to be declared at the beginning of the method. The scope of a local variable begins at the point it is declared and terminates at the end of the method. When a program enters a section of code where a variable has scope, that variable has come into scope, which means the variable is visible to the program. Example: VariableScope.javaVariableScope.java

Copyright © Slide #39 The Conditional Operator The conditional operator is a ternary (three operand) operator. The conditional operator allows a programmer to write a simple if-else type statement. The format of the operators is: expression1 ? expression2 : expression3 The conditional operator can also return a value.

Copyright © Slide #40 The Conditional Operator The conditional operator can be used as a shortened if-else statement: x > y ? z = 10 : z = 5; This line is functionally equivalent to: if(x > ) z = 10; else z = 5;

Copyright © Slide #41 The Conditional Operator Many times, the conditional operator is used to supply a value. number = x > y ? 10 : 5; This is functionally equivalent to: if(x > y) number = 10; else number = 5; Example: ConsultantCharges.javaConsultantCharges.java

Copyright © Slide #42 The switch Statement The if-else statements allow the programmer to make true / false branches. The switch statement allows the programmer to use an ordinal value to determine how a program will branch. The switch statement can evaluate an integer type or character type variable and make decisions based on the value.

Copyright © Slide #43 The switch Statement The switch statement takes the form: switch (SwitchExpression) { case CaseExpression: // place one or more statements here break; case CaseExpression: // place one or more statements here break; // case statements may be repeated //as many times as necessary default: // place one or more statements here }

Copyright © Slide #44 The switch Statement The switch statement takes an ordinal value (byte, short, int, long, char) as the SwitchExpression. switch (SwitchExpression) { … } The switch statement will evaluate the expression. If there is an associated case statement that matches that value, program execution will be transferred to that case statement.

Copyright © Slide #45 The switch Statement Each case statement will have a corresponding CaseExpression that must be unique. case CaseExpression: // place one or more statements here break; If the SwitchExpression matches the CaseExpression, the Java statements between the colon and the break statement will be executed.

Copyright © Slide #46 The switch Case The break statement ends the case statement. The break statement is optional. If a case does not contain a break, then program execution continues into the next case. Example: NoBreaks.javaNoBreaks.java Example: PetFood.javaPetFood.java The default case is optional and will be executed if no CaseExpression matches the SwitchExpression. Example: SwitchDemo.javaSwitchDemo.java

Copyright © Slide #47 The DecimalFormat Class When printing out double and float values, the full fractional value will be printed. The DecimalFormat class can be used to format these values. In order to use the DecimalFormat class, the Java import statement must be used. At the top of the program the statement import java.text.DecimalFormat; must be used. Examples: Format1.javaFormat1.java, Format2.java, Format3.java, Format4.javaFormat2.javaFormat3.javaFormat4.java

Copyright © Slide #48 The SalesCommission Class SalesCommision - sales : double - rate : double - commission : double - advance : double - pay : double + SalesCommission(s: double, a: double) : - setRate() : void -calculatePay() : void + getPay() : double + getCommission() : double + getRate() : double + getAdvance() : double + getSales() : double Example Files: SalesCommission.java

Copyright © Slide #49 Method Decomposition Using Private Methods Long methods can be broken up into shorter more specialized methods, known as helper or utility methods. Each method should perform a small, well- defined task. Sensitive tasks can be broken into private methods. Private methods are available only to other methods within the class.

Copyright © Slide #50 Main Programs The SalesCommision class is a utility class. It provides an abstraction of the data and methods needed to calculate a sales commission. The program that utilizes this class is called the Main program. Example: HalsCommission.javaHalsCommission.java