Download presentation
Presentation is loading. Please wait.
Published byCarol Tucker Modified over 9 years ago
1
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional
2
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Put on the Desktop: SwitchClass.java NestedIF.java DriverConditional.java Months.java
3
©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.
4
©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.
5
©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.
6
©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”);
7
©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
8
©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.
9
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 5.1 Mapping of the sample if statement to the general format.
10
©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
11
©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
12
©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
13
©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.
14
©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.
15
©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!
16
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. 5.2 Boolean Expressions and Variables Boolean operators and their meanings:
17
©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;
18
©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); }
19
©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.”); }
20
©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
21
©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
22
©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
23
©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
24
©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’;
25
©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
26
©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
27
©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.
28
©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.
29
©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))
30
©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.
31
©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.
32
©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.
33
©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.
34
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. The Semantics of ==
35
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. In Creating String Objects
36
©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; }
37
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Fig. 5.6 Mapping of the sample switch statement to the general format.
38
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. The switch Statement The syntax for the switch statement is switch ( ){ :... : }
39
©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.
40
©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.
41
©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.
42
©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.
43
©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"); }
44
©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"); }
45
©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 1 2 3 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
46
©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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.