©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.

Slides:



Advertisements
Similar presentations
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 5 Selection Statements Animated Version.
Advertisements

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 5 Selection Statements.
3 Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. Conditions can be formed using the.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 4: Selections.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 3 Control Statements.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Animated Version.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to Implement a selection control.
Introduction to Java Programming, 4E Y. Daniel Liang.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Selection Statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
C++ for Engineers and Scientists Third Edition
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Control Statements.
Chapter Chapter 5 Selection Statements. Objectives Understand selection control statement –if statements –switch statements Write boolean expressions.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved.1 Chapter 3 Selections.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
CPS120: Introduction to Computer Science Decision Making in Programs.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
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.
Introduction to Control Statements JavaScript – Part 3 George Mason University June 3, 2010.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 05 (Part III) Control Statements: Part II.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
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.
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Objectives After you have read and studied this chapter, you should be able to Implement a selection control using if statements Implement a.
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 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
CPS120: Introduction to Computer Science Decision Making in Programs.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
Control Statements: Part1  if, if…else, switch 1.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Introduction to Control Statements IT108 George Mason University.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 3 Selections Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved
Chapter 3 Control Statements
Selections Java.
CHAPTER 4 Selection CSEG1003 Introduction to Computing
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 3 Selections Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Chapter 4: Control Structures I (Selection)
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
Control Structure Chapter 3.
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Chapter 6 Selection Statements
Controlling Program Flow
Presentation transcript:

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Put on the Desktop: SwitchClass.java NestedIF.java DriverConditional.java Months.java

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 5 Objectives After you have read and studied this chapter, you should be able to Implement selection control in a program by using if statements. Implement selection control in a program by using switch statements. Write boolean expressions with relational and boolean operators. Evaluate given boolean expressions correctly.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 5 Objectives, cont. After you have read and studied this chapter, you should be able to Nest an if statement inside another if statement’s then or else part correctly. Describe how objects are compared. Choose the appropriate selection control statement for a given task.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.1 The if Statement Statements in programs are executed in sequence. We can add decision- making statements to a program to alter the control flow. The statement that alters the control flow is called a control statement.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.1 The if Statement The if statement is one type of selection statement. InputHandler input = new InputHandler(); int testScore = input.getInteger(“Enter test score:”); if (testScore < 70) JOptionPane.showMessageDialog(“You did not pass”); else JOptionPane.showMessageDialog(“You did pass”);

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.1 The if Statement The if statement specifies which block of code to execute, depending on the result of evaluating a test condition called a boolean expression. if ( ) else

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.1 The if Statement The is a conditional expression that is evaluated to either true or false.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 5.1 Mapping of the sample if statement to the general format.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.1 The if Statement The six relational operators we can use in conditional expressions are: <less than <=less than or equal to ==equal to !=not equal to > greater than >=greater than or equal to

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 5.2 The diagram showing the control flow of the sample if statement. One entry point and one exit point

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.1 The if Statement The if statement does not have to contain a block of code for the else condition. In the if-then structure, no special instructions are executed if the boolean expression evaluates to false. if (testScore >=95){ JOptionPane.showMessageDialog(“You are an honor student”);} else { } //not needed

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Caution Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); //WRONG { area = radius*radius*PI; System.out.println( "The area for the circle of radius " + radius + " is " + area); } This mistake is hard to find, because it is not a compilation error or a runtime error, it is a logic error. This error often occurs when you use the next-line block style.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 5.3 The diagram showing the control flow of the second version of the if statement.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.2 Boolean Expressions and Variables A boolean operator takes boolean values as its operands and returns a boolean value. The three boolean operators are and:&& or:|| not!

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.2 Boolean Expressions and Variables Boolean operators and their meanings:

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.2 Boolean Expressions and Variables The result of a boolean expression is either true or false. These are the two values of data type boolean. We can declare a variable of data type boolean and assign a boolean value to it. boolean pass, done; pass = 70 < x; done = true;

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.2 Boolean Expressions and Variables The boolean expression is enclosed in parentheses for all forms of the if statement. Example: if ( (i > 0) && (i < 20) ) { System.out.println(“i is an integer between 0 and 20); }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.2 Boolean Expressions and Variables Determine whether a number is even or odd: … // convert string into int int number = Integer.parseInt(inStr); if (number % 2 ==0) { System.out.println( number + “ is even.”); } if (number % 2 !=0) { System.out.println( number + “ is odd.”); }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.2 Boolean Expressions and Variables Caution To test whether a boolean variable is true or false in a test condition, it is redundant to use equality comparison operator like this: if (even == true) System.out.println(“ It is even”); Instead, it is better to use the boolean variable directly, as follows: if (even) System.out.println(“ It is even”); INCORRECT -An error that is difficult to detect if (even = true) // This is an assignment not a test for equality System.out.println(“ It is even”); Note: This statement DOES NOT have syntax errors. It assigns true to even so that even is always true

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.2 Boolean Expressions and Variables Evaluate the following boolean expressions. a. 3 < 4 || 5 ==5 // true b. 2 < 4 && ( 5 <=2) // false

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.2 Boolean Expressions and Variables Consider the following expression: x / y > z || y == 0 What will the result be if y is equal to 0? Get a runtime error called an arithmetic exception x / y causes a divide-by-zero error However, if we reverse the order to y == 0 || x / y > z short-circuit evaluation(|| and && operators): No arithmetic exception will occur because the test for the right operand x / y > z will not be evaluated

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.3 Nested-if Statements An if statement that contains another if statements in either its then or else block is called a nested-if statement. if (testScore >= 70) { if (studentAge < 10) { System.out.println(“You did a great job”); } // end else else // test score >=70 and age >=10 { System.out.println(“You did pass”); } // end else } //end if testscore >= 70 else //test score < 70 { System.out.println(“You did not pass”); }//end else test score < 70 Run NestedIF.java

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Multiple Alternative if Statements (Nested if statements) if (score >= 90) grade = ‘A’; else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’; else if (score >= 60) grade = ‘D’; else grade = ‘F’;

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Multiple Alternative if Statements (Nested if statements) if (score >= 90) grade = ‘A’; else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’; else if (score >= 60) grade = ‘D’; else grade = ‘F’; Preferred writing style

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. The else clause matches the most recent if clause in the same block. For example, the following statements: int i = 1; int j = 2; int k = 3; if (i > j) //false, skip the next if and else statement if (i > k) System.out.println("A and something else"); else System.out.println("B and something else"); is equivalent to int i = 1; int j = 2; int k = 3; if (i > j) //false skip the next if and else statements if (i > k) System.out.println("A"); else System.out.println("B"); //Note: Nothing is printed

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Note Nothing is printed from the preceding statement. To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) System.out.println("A"); } else System.out.println("B"); // This statement prints // B.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 5.4 A diagram showing the control flow of the example nested-if statement.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Comparing Objects With primitive data types, we have only one way to compare them, but with objects (reference data type), we have two ways to compare them. 1. We can test whether two variables point to the same object (use ==), or 2. We can test whether two distinct objects have the same contents. if (string1.equals(string2))

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.4 Comparing Objects When two primitive variables are compared, we are comparing their contents. In the case of objects, the content is the address where the object is stored. The best approach for comparing objects is to define comparison methods for the class.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Using == With Objects (Sample 1) String str1 = new String("Java"); String str2 = new String("Java"); if (str1 == str2) { System.out.println("They are equal"); } else { System.out.println("They are not equal"); } They are not equal Not equal because str1 and str2 point to different String objects.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Using == With Objects (Sample 2) String str1 = new String("Java"); String str2 = str1; //point to the same object if (str1 == str2) { System.out.println("They are equal"); } else { System.out.println("They are not equal"); } They are equal It's equal here because str1 and str2 point to the same object.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Using equals with String String str1 = new String("Java"); String str2 = new String("Java"); if (str1.equals(str2)) { System.out.println("They are equal"); } else { System.out.println("They are not equal"); } They are equal It's equal here because str1 and str2 have the same sequence of characters.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. The Semantics of ==

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. In Creating String Objects

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.5 The switch Statement The switch statement provides an efficient way to evaluate and process multiple options. Arithmetic expression must be char, byte, short, or int. switch (gradeLevel){ case 1: System.out.println(“Go to the gymnasium”); break; case 2: System.out.println(“Go to the Science Auditorium”); break; case 3: System.out.println(“Go to Halligan Hall Room 104”); break; case 4: System.out.println(“Go to Root Hall Room 101”); break; }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 5.6 Mapping of the sample switch statement to the general format.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. The switch Statement The syntax for the switch statement is switch ( ){ :... : }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. The switch Statement The data type of must be char, byte, short, or int. The value of is compared against the constant i of. If there is a matching case, its case body is executed. Otherwise, the execution continues to the statement following the switch statement.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. The switch Statement 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.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 5.7 A diagram showing the control flow of the switch statement with and without the break statements.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.5 The switch Statement It is good practice to implement a default case in a switch statement. The default case will be executed if there is no matching case. Such a style of programming is characterized as defensive programming.

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. The switch Statement The switch handles multiple conditions more efficiently than multiple if/else statements. Add a default statement. switch (year) { case 7: annualInterestRate = 7.25; break; case 15: annualInterestRate = 8.50; break; case 30: annualInterestRate = 9.0; break; default: System.out.println( "Wrong number of years, enter 7, 15, or 30"); }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. The switch Statement Do not forget to use a break statement when one is needed. For example, the following code always displays “Wrong number of years” regardless of what numOfYears is. Suppose the numOfYears is 15. The statement annualInterestRate = 8.50 is executed, then the statement annualInterestRate = 9.0, and finally the statement System.out.println("Wrong number of years"). switch (numOfYears) { case 7: annualInterestRate = 7.25; case 15: annualInterestRate = 8.50; case 30: annualInterestRate = 9.0; default: System.out.println("Wrong number of years"); }

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. The switch Statement Do not forget to use a break statement when one is needed. Suppose: int selection = 1; switch (selection) { case 0: System.out.println(0); case 1: System.out.println(1); case 2: System.out.println(2); case 3: System.out.println(3); } When this code is executed, the output is Because after the statement in case 1 is executed, statements in the remaining cases will be executed also. Note: If you enter anything other than 0,1,2,3, nothing will be printed Run SwitchClass on the M: drive in the Sample Programs folder

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. The Conditional Statement You might want to assign a value to a variable that is restricted by certain conditions if (x > 0) //true y = 1; else y = -1; //false is equivalent to y = (x > 0) ? 1 : -1; 1 for true condition -1 for false cndition