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.

Slides:



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

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.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
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.
Chapter 4 Making Decisions
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
The switch Statement, DecimalFormat, and Introduction to Looping
11 Chapter 3 DECISION STRUCTURES CONT’D. 22 FORMATTING FLOATING-POINT VALUES WITH THE DecimalFormat CLASS We can use the DecimalFormat class to control.
© 2012 Pearson Education, Inc. All rights reserved. Chapter 3: Decision Structures Starting Out with Java: From Control Structures through Data Structures.
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
Chapter 3 Decision Structures Starting Out with Java: From Control Structures through Objects.
Chapter 4 Selection Structures: Making Decisions.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
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. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
1 Boolean Expressions to Make Comparisons Boolean expression –Represents only one of two states –Expression evaluates to either true or false Expressions.
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.
Chapter 4 Making Decision Csc 125 C++ programming language Fall 2005.
Control Stuctures Module 4 Copyright © Copyright © Slide #2 Decision Structures Chapter Objectives To understand: how to write boolean expressions.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Copyright 2003 Scott/Jones Publishing Making Decisions.
Chapter 3: Decision Structures
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
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.
Chapter Making Decisions 4. Relational Operators 4.1.
CHAPTER 5 MAKING DECISION Hidayah Elias BFC2042 – Computer Programming.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC INTRO TO COMPUTING - PROGRAMMING If Statement.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
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 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
CHAPTER 3 Decision Structures Copyright © 2016 Pearson Education, Ltd.
CS0007: Introduction to Computer Programming
Java Programming Fifth Edition
The if…else Selection Statement
Chapter 3: Decision Structures by Tony Gaddis and Godfrey Muganda
Chapter 4: Making Decisions.
Chapter 3: Decision Structures
Selections Java.
The switch Statement, and Introduction to Looping
Chapter 4: Making Decisions.
Lecture 3- Decision Structures
Topics The if Statement The if-else Statement Comparing Strings
Chapter 4: Making Decisions.
Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz
Chapter 4: Making Decisions.
Chapter 3: Decision Structures
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Chapter 3: Decision Structures
Topics The if Statement The if-else Statement Comparing Strings
Chapter 8 JavaScript: Control Statements, Part 2
Chapter 3:Decision Structures
The System.exit() Method
Boolean Expressions to Make Comparisons
Presentation transcript:

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 6.Comparing String Objects 7.More about Variable Declaration and Scope 2

Contents (Cont’d) 8.The Conditional Operators 9.The Switch Statement 10.Creating Objects with the DecimalFormat Class 11.The printf Method 3

1. The if Statement  Problem: Write a program to calculate user’s average of 3 test scores. If the average is greater than 95, the program congratulates the users on obtaining a high score. 4

1. The if Statement (Cont’d) 5

6

 Simple decision structure logic 7

1. The if Statement (Cont’d) if(BooleanExpression) statement; The BooleanExpression must be a boolean expression A boolean expression is either true or false If the BooleanExpression is true, the very next statement is executed. Otherwise, it is skipped. The statement is conditionally executed because it only executes under the condition that the expression in the parentheses is true. 8

Using Relational Operators to Form Conditions  Typically, the boolean expression is formed with a relational operator (binary operator. 9 Relational Operators (in order of precedence) Meaning >Greater <Less than >=Greater than or equal to <=Less than or equal to ==Equal to !=Not equal to

Using Relational Operators to Form Conditions (Cont’d)  Assuming that a is 4, b is 6, and c is 4 b>=a true c<=a true a>=5 false c==6false b!=6false 10

Programming Style and the if Statement  Two important style rules The conditionally executed statement should appear on the line after the if statement. The conditionally executed statement should be indented on level from the if statement. if(value>32) System.out.println(“Invalid number”); if(value>32) System.out.println(“Invalid number”); 11

Be Careful with Semicolons if(BooleanExpression) statement; int x = 0, y = 10; if(x > y); System.out.println(x + “is greater than “ + y); 12 No semicolon here Semicolon goes here It will always execute.

Multiple Conditionally Executed Statements  Enclosing a group of statements by braces if(sales > 5000) { bonus = 500.0; commissionRate = 0.12; dayOff += 1; } 13 These three statements are executed if sales is greater than 5000

Comparing Characters  Using the relational operators to test character data as well as number  Assuming ch is a char variable: Compare ch to the character ‘A’: if(ch==‘A’) System.out.println(“The letter is A.”); Compare the ch is not equal to ‘A’: if(ch!=‘A’) System.out.println(“Not the letter is A.”); 14

Comparing Characters (Cont’d)  In Unicode, letters are arranged in alphabetic order: ‘A’ comes before ‘B’, the numeric code of ‘A’ (65) is less than the code of ‘B’ (66). ‘A’ < ‘B’ true  In Unicode, the uppercase letters come before the lowercase letter. 15

2. The if-else statement  Problem Write a program to get two numbers and divide the first number by the second number. 16

2. The if-else statement 17

18

2. The if-else statement 19

Logic of the if-else Statement 20

Logic of the if-else Statement (Cont’d)  The if-else statement will execute one group of statement if its boolean expression is true, or another group if its boolean expression is false. if(BooleanExpression) statement or block else statement or block 21

3. The if-else-if Statement  Problem Write a program to ask the user to enter a numeric test score. Display a letter grade (A, B, C, D, or F) for the score. score < 60 F 60 <= score < 70 D 70 <= score < 80 C 80 <= score < 90 B 90 <= score <= 100 A score > 100Invalid score 22

23

24

Logic of the if-else-if Statement 25 Logic of the if- else-if Statement

3. The if-else-if Statement  The if-else-if statement is a chain of if-else statements. Each statement in the chain performs its test until one of the tests is found to be true. if(BooleanExpression) statement or block else if(BooleanExpression) statement or block // //Put as many else if statement as needed here // else statement or block 26

4. Nested if Statement  Problem Write a Java program to determine whether a bank customer qualifies for a loan. To qualify, a customer must earn at least $30,000 per year, and must have been on his or her current job for at least two years. 27

4. Nested if Statement  Input User’s annual salary Number of years at the current job 28

29

30

4. Nested if Statement (Cont’d)  An if statement appears inside another if statement, it is considered nested.  The rule for matching else clauses with if clauses is this: An else clause goes with the closet previous if clause that doesn’t already have its own else clause. 31

Alignment of if and else clauses 32

5. Logical Operators  Logical operators connect two or more relational expressions into one or reverse the logic of an expression.  Java provides two binary logical operators && : AND ||: OR one unary logical operator !: NOT 33

5. Logical Operators (Cont’d) 34 OperatorMeaningEffect && ANDConnects two boolean expression into one. Both expressions must be true for the overall expression to be true. || ORConnects two boolean expression 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. ! NOTReverses 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 return true.

5. Logical Operators (Cont’d) ExpressionMeaning x > y && a < b Is x greater than y AND is a less than b ? x == y || x == z Is x equal to y OR is x equal to z ? !(x > y) Is the expression x > y NOT true ? 35

The && Operator  The && performs short-circuit evaluation If the expression on the left side of the && operator is false, the expression on the right side will not be checked. 36 xyx && y true false truefalse

The && Operator (Cont’d)  A different version of the LoanQualifier program 37

38

The || Operator  The || performs short-circuit evaluation If the expression on the left side of the || operator is true, the expression on the right side will not be checked. 39 xyX || y true falsetrue falsetrue false

The || Operator  Problem Write a Java program to determine whether a bank customer qualifies for a loan. To qualify, a customer must earn at least $30,000 per year, OR must have been on his or her current job for at least two years. 40

The || Operator (Cont’d)  Input User’s annual salary Number of years at the current job 41

A Better Solution 42

43

The ! Operator  The ! Operator performs a logical NOT operation  !(x > 1000)x <= x!x truefalse true

The Precedence and Associativity of Logical Operators  The logical operators have orders of precedence and associativity.  The precedence of the logical operators, from highest to lowest ! && ||  !(x > 2) Applies the ! operator to the expression x > 2  !x > 2 Causes a compiler error 45

The Precedence and Associativity of Logical Operators (Cont’d)  The && and || operators rank lower in precedence than the relational operators (a > b) && (x b && x < y (x == y) || (b > a) x == y || b > a  The logical operators evaluate their expression from left to right a < b || y == z a < b is evaluated before y == z a j y == z is evaluated first because the && operator has higher precedence than || Is equivalent to the following (a j)) 46

The Precedence and Associativity of Logical Operators (Cont’d) Order of Precedence Operators 1 - (unary negation) ! 2 * / % 3 + = 4 = 5 == != 6 && 7 || 8 = += -= *= /= %= 47

Checking Numeric Ranges with Logical Operators  Determining whether a numeric value is within a specific range of values Using the && operator x >= 20 && x <= 40  Determining whether a numeric value is outside a specific range of values Using the || operator x 40 48

6. Comparing String Objects  We cannot use relational operators to compare String objects. Instead we must use a String method. String name1 = “Marks”; String name2 = “Mary”;  name1 == name2 will be false because the variables name1 and name2 reference different objects. 49

6. Comparing String Objects if(name1 == name2) 50

6. Comparing String Objects  To compare the contents of two String objects correctly using the method equals of String class if(name1.equal(name2)) The equals method returns true if they are the same, or false if they are not the same. 51

52

6. Comparing String Objects  Comparing String objects to string literals Pass the string literal as the argument to the equals method if(name1.equals(“Mark”)) 53

6. Comparing String Objects  The compareTo method of the String class To determine whether one string is greater than, equal to, or less than another string. StringReference.compareTo(OtherString) StringReference is a variable that references a String object, OtherString is either another variable that references a String object or a string literal. 54

6. Comparing String Objects  If the method’s return value < 0 : the string referenced by StringReference is less than the OtherString argument 0 : The two strings are equal. > 0 : the string referenced by StringReference is greater than the OtherString argument 55

6. Comparing String Objects 56

6. Comparing String Objects  String comparison of “Mary” and “Mark” The character ‘y’ is greater than ‘k’, so “Mary” is greater than “Mark”. 57

Ignore Case in String Comparisons  The equals and compareTo methods perform case sensitive comparisons. In other words, “A” is not the same as “a”.  The String class provides the equalsIgnoreCase and compareToIgnoreCase methods The case of characters in strings is ignored. 58

7. More about Variable Declaration and Scope  The scope of a variable is limited to the block in which it is declared.  It is a common practice to declare all of a method’s local variables at the beginning of the method, it is possible to declare them at later points. Sometimes programmers declare certain variables near the part of the program where they are used in order to make their purpose more evident. 59

7. More about Variable Declaration and Scope  A local variable’s scope always starts at the variable’s declaration ends at the closing brace of the block of code in which it is declared. 60

7. More about Variable Declaration and Scope 61

The Conditional Operator  The conditional operator (a ternary operator) is used to create short expressions that work like if-else statements. Expression1 ? Expression2 : Expression3  Exprerssion1 is a boolean expression. If Expression1 is true, then Expression2 is executed. Otherwise Expression3 is executed. 62

The Conditional Operator (Cont’d) x < 0 ? y = 10 : z = 20; if(x < 0) y = 10; else z = 20; 63

The Conditional Operator (Cont’d)  We can put parentheses around the subexpressions in a conditional expression (x < 0) ? (y = 10) : (z = 20); 64

Using the Value of a Conditional Expression  The conditional expression also returns a value.  If Expression1 is true, the value of the conditional expression is the value of Expression2. Otherwise it is the value of Expression3. number = x > 100 ? 20 : 50; 65

Using the Value of a Conditional Expression (Cont’d) number = x > 100 ? 20 : 50; if(x > 100) number = 20; else number = 50; 66

Using the Value of a Conditional Expression (Cont’d) System.out.println(“Your grade is: “ + (score < 60 ? “Fail” : “Pass”)); if(score < 60) Systym.out.println(“Your grade is: Fail.“); else Systym.out.println(“Your grade is: Pass.“); 67

7. The switch Statement  The switch statement lets the value of a variable or expression determine where the program will branch to.  The if-else-if statement allows the program to branch into one of several possible paths. It tests a series of boolean expressions, and branches if one of those expression is true. 68

7. The switch Statement (Cont’d)  The switch statement tests the value of an integer or character expression and then uses that value to determine which set of statements to branch to. 69

7. The switch Statement (Cont’d) switch(SwitchExpression) { case CaseExpression1: // place one or more statements here break; case CaseExpression2: // place one or more statements here break; // case statements may be repeated as many // times as necessary default: // place one or more statements here } 70

7. The switch Statement (Cont’d)  The SwitchExpression is an expression that must result in a value of one of these types: char, byte, short, or int.  The CaseExpression is a literal or a final variable which must be of the char, byte, short, or int types.  The CaseExpressions of each case statement must be unique.  The default section is optional. If we leave it out, the program will have nowhere to branch to if the SwitchExpression doesn’t match any of CaseExpressions. 71

7. The switch Statement (Cont’d) if(SwitchExpression == CaseExpression1) // place statement here else if(SwitchExpression == CaseExpression2) // place statement here // else if statements may be repeated // as many times as necessary else // place statement here 72

7. The switch Statement (Cont’d) 73

74

7. The switch Statement (Cont’d)  The case statements show where to start executing in the block and the break statements show the program where to stop.  Without break statements, the program would execute all of the lines from the matching case statement to the end of the block.  The default section (or the last case section if there is no default) does not need a break statement. 75

Without break Statement  Without break statement, the program falls through all the statements below the one with the matching case expression. 76

Without break Statement 77

78

Without break Statement !  Write a program that asks the user to select a grade of pet food. The available choices are A, B, and C. The program will recognize either uppercase or lowercase letters. 79

Without break Statement 80

81

10. Creating Objects with the DecimalFormat class  DecimalFormat class can be used to format the appearance of floating-point numbers rounded to a specified number of decimal places.  In Java, a value of the double type can be displayed with as many as 15 decimal places, and a value of float type can be displayed with up to 6 decimal places. 82

10. Creating Objects with the DecimalFormat class (Cont’d) double number; number = 10.0/6; System.out.println(number);  How to control the number of decimal places that are displayed ? 83

10. Creating Objects with the DecimalFormat class (Cont’d)  Using the DecimalFormat class import java.text.DecimalFormat; Create an object of the DecimalFormat class DecimalFormat formatter; formatter = new DecimalFormat(“#0.00”);  Constructor Is automatically executed To initialize the object’s attributes with appropriate data and perform any necessary setup operations. 84 constructor format pattern

10. Creating Objects with the DecimalFormat class (Cont’d)  #: specifies that a digit should be displayed if it is present. If there is no digit in this position, no digit should be displayed.  0: specifies that a digit should be displayed in this position if it is present. If there is no digit in this position, a 0 should be displayed. 85

“#0.00” 86

“000.00” 87

“#,##0.00” 88

“#0%”  Formatting numbers as percentages Writing the % character at the last position in the format pattern. This causes a number to be multiplied by 100, and the % character is appended to its end. 89

“#0%” 90

The printf Method  The System.out.printf method allows you to format output in a variety of ways. System.out.printf(FormatString, ArgumentList) 91 contains text and/or special formatting specifiers. is a list of zero or more additional arguments.

Format Specifiers  %d : For a decimal integer int hours = 40; System.out.printf(“I worked %d hours this week.\n”, hours); I worked 40 hours this week. int dogs = 2; int cats = 4; System.out.printf(“We have %d dogs and %d cats.\n”, dogs, cats); We have 4 dogs and 2 cats. 92

Format Specifiers  %nd : the number should be printed in a field that is n places wide. int nunber = 9; System.out.printf(“The value is %6d.\n”, number); The value is 9. If the field is wider than the specified width, the field width will be expanded to accommodate the value. int nunber = 97654; System.out.printf(“The value is %2d.\n”, number); The value is

Format Specifiers  %f : to print a floating-point number double nunber = ; System.out.printf(“The value is %f.\n”, number); The value is double nunber = ; System.out.printf(“The value is %18f.\n”, number); The value is ; double nunber = ; System.out.printf(“The value is %8.2f.\n”, number); The value is

Format Specifiers double nunber = ; System.out.printf(“The value is %,.2f.\n”, number); The value is 1,253,  %s : To print a string argument String name = “Ringo”; System.out.printf(“My name is %s.\n”, name); My name is Ringo. String name = “Ringo”; System.out.printf(“My name is %10s.\n”, name); My name is Ringo. 95