Download presentation
Presentation is loading. Please wait.
1
Chapter 6 Selection Statements
5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
2
Introduction to Object-Oriented Programming with Java--Wu
Chapter 6 Chapter 6 Objectives After you have read and studied this chapter, you should be able to Implement selection control in a program using if statements. Implement selection control in a program using switch statements. Write boolean expressions using relational and boolean operators. Evaluate given boolean expressions correctly. Nest an if statement inside another if statement’s then or else part correctly. Choose the appropriate selection control statement for a given task. Write applications using the ListBox class from javabook and the Color class from the standard java.awt package. 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
3
Introduction to Object-Oriented Programming with Java--Wu
Chapter 6 The if Statement //Assume messageBox and inputBox are declared and created //Assume testScore is declared testScore = inputBox.getInteger("Enter test score:"); if (testScore < 70) messageBox.show("You did not pass"); else messageBox.show("You did pass"); This statement is executed if the testScore is less than 70. This statement is executed if the testScore is 70 or higher. 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
4
Syntax for the if Statement (if-then-else)
Chapter 6 Syntax for the if Statement (if-then-else) if ( <boolean expression> ) <then block> else <else block> Boolean Expression if ( testScore < ) messageBox.show("You did not pass"); else messageBox.show("You did pass"); Then Block Else Block 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
5
Introduction to Object-Oriented Programming with Java--Wu
Chapter 6 Control Flow testScore < 70 ? messageBox.show ("You did pass"); false messageBox.show ("You did not pass"); true 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
6
Introduction to Object-Oriented Programming with Java--Wu
Chapter 6 Relational Operators < //less than <= //less than or equal to == //equal to != //not equal to > //greater than >= //greater than or equal to testScore < 80 testScore * 2 >= 350 30 < w / (h * h) x + y != 2 * (a + b) 2 * Math.PI * radius <= One very common error in writing programs is mixing up the assignment and equality operators. We frequently make a mistake of writing if (x = 5) ... when we actually wanted to say if (x == 5) ... 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
7
Introduction to Object-Oriented Programming with Java--Wu
Chapter 6 Compound Statements Use braces if the <then> or <else> block has multiple statements. if (testScore < 70) { messageBox.show("You did not pass"); messageBox.show("Try harder next time"); } else messageBox.show("You did pass"); messageBox.show("Keep up the good work"); Then Block Rules for writing the then and else blocks: - Left and right braces are necessary to surround the statements if the then or else block contains multiple statements. - Braces are not necessary if the then or else block contains only one statement. - A semicolon is not necessary after a right brace. Else Block 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
8
Introduction to Object-Oriented Programming with Java--Wu
Chapter 6 Style Guide if ( <boolean expression> ) { … } else { Style 1 if ( <boolean expression> ) { … } else Style 2 In this book, we will use Style 1, mainly because this style is more common among programmers. If you prefer Style 2, then go ahead and use it. Whichever style you choose, be consistent, because consistent look and feel are very important to make your code readable. 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
9
Introduction to Object-Oriented Programming with Java--Wu
Chapter 6 The if-then Statement if ( <boolean expression> ) <then block> Boolean Expression if ( testScore >= ) messageBox.show("You are an honor student"); Then Block Notice that the if–then statement is not necessary, because we can write any if–then statement using if–then–else by including no statement in the else block. For instance, the sample if–then statement can be written as if (testScore >= 95) { messageBox.show("You are an honor student"); } else { } In this book, we use if-then statements whenever appropriate. 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
10
Control Flow of if-then
Chapter 6 Control Flow of if-then testScore >= 95? messageBox.show ("You are an honor student"); true false 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
11
Boolean Expressions and Variables
Chapter 6 Boolean Expressions and Variables A B A && B A || B !A false true The AND operation results in true only if both A and B are true. The OR operation results in true if either A or B is true. The NOT operation is true if A is false and false if A is true. Combining boolean operators with relational and arithmetic operators, we can come up with a long boolean expression such as (x + 150) == y || x < y && !(y < z && z < x) In mathematics, we specify the range of values for a variable as 80 x < 90 In Java, to test that the value for x is within the specified lower and upper bounds, we express it as 80 <= x && x < 90 You cannot specify it as 80 <= x < 90 which is a syntax error because the relational operators (<, <=, etc.) are binary operators whose operands must be numerical values. Notice that the result of the subexpression 80 <= x is a boolean value, which cannot be compared to the numerical value 90. Their data types are not compatible. 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
12
Introduction to Object-Oriented Programming with Java--Wu
Let’s Try one… Page 237, #2 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu
13
Short-Circuit Evaluation
Chapter 6 Short-Circuit Evaluation Consider the following boolean expression: x > y || x > z The expression is evaluated left to right. If x > y is true, then there’s no need to evaluate x > z because the whole expression will be true whether x > z is true or not. To stop the evaluation once the result of the whole expression is known is called short-circuit evaluation. What would happen if the short-circuit evaluation is not done for the following expression? z == 0 || x / z > 20 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
14
Introduction to Object-Oriented Programming with Java--Wu
What about this? if (70 <= x & x < 90) versus if (70 <= x && x < 90) OR if (70 <= x | x < 90) if (70 <= x || x < 90) 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu
15
Operator Precedence Rules
Chapter 6 Operator Precedence Rules 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
16
The Nested-if Statement
Chapter 6 The Nested-if Statement The then and else block of an if statement can contain any valid statements, including other if statements. An if statement containing another if statement is called a nested-if statement. if (testScore >= 70) { if (studentAge < 10) { messageBox.show("You did a great job"); } else { messageBox.show("You did pass"); //test score >= 70 } //and age >= 10 else { //test score < 70 messageBox.show("You did not pass"); It is possible to write if tests in different ways to achieve the same result. For example, the above code can also be expressed as if (testScore >= 70 && studentAge < 10) { messageBox.show("You did a great job"); } else { //either testScore < 70 OR studentAge >= 10 if (testScore >= 70) { messageBox.show("You did pass"); messageBox.show("You did not pass"); 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
17
Control Flow of Nested-if Statement
Chapter 6 Control Flow of Nested-if Statement testScore >= 70 ? inner if messageBox.show ("You did not pass"); false true studentAge < 10 ? messageBox.show ("You did pass"); false messageBox.show ("You did a great job"); true 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
18
Writing a Proper if Control
Chapter 6 Writing a Proper if Control if (num1 < 0) if (num2 < 0) if (num3 < 0) negativeCount = 3; else negativeCount = 2; negativeCount = 1; negativeCount = 0; negativeCount = 0; if (num1 < 0) negativeCount++; if (num2 < 0) if (num3 < 0) The statement negativeCount++; increments the variable by one The statement negativeCount++; increments the variable by one and, therefore, is equivalent to negativeCount = negativeCount + 1; The double plus operator (++) is called the increment operator, and the double minus operator (--) is the decrement operator (which decrements the variable by one). 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
19
Introduction to Object-Oriented Programming with Java--Wu
Chapter 6 if – else if Control if (score >= 90) messageBox.show("Your grade is A"); else if (score >= 80) messageBox.show("Your grade is B"); else if (score >= 70) messageBox.show("Your grade is C"); else if (score >= 60) messageBox.show("Your grade is D"); else messageBox.show("Your grade is F"); Test Score Grade 90 score A 80 score 90 B 70 score 80 C 60 score 70 D score 60 F If we follow the general rule, the above if-else if will be written as below, but the style shown in the slide is the standard notation. if (score >= 90) messageBox.show("Your grade is A"); else if (score >= 80) messageBox.show("Your grade is B"); if (score >= 70) messageBox.show("Your grade is C"); if (score >= 60) messageBox.show("Your grade is D"); messageBox.show("Your grade is F"); 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
20
Introduction to Object-Oriented Programming with Java--Wu
Chapter 6 Matching else Watch out for the dangling else! Are and different? A B if (x < y) if (x < z) messageBox.show("Hello"); else messageBox.show("Good bye"); A if (x < y) { if (x < z) { messageBox.show("Hello"); } else { messageBox.show("Good bye"); Both and means… A B if (x < y) if (x < z) messageBox.show("Hello"); else messageBox.show("Good bye"); B If you want the else to match with the first if, then you have to write if (x < y) { if (x < z) messageBox.show("Hello"); } else messageBox.show("Good bye"); Always use the {} and indentation. 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
21
Introduction to Object-Oriented Programming with Java--Wu
ListBox The ListBox class provides a list of items the user can select. It is considered a better user interface to allow the user to enter only valid values instead of detecting invalid entries after the user entered them. First we create a ListBox object as MainWindow mainWindow = new MainWindow( ); ListBox colorList = new ListBox( mainWindow, “Select Color” ); We can create colorList as … = new ListBox( mainWindow ); if we do not need a customized dialog title. 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu
22
Introduction to Object-Oriented Programming with Java--Wu
Chapter 6 ListBox – Add Items After we create a ListBox object, we add items to it as colorList.addItem("Magenta"); colorList.addItem("Cyan"); colorList.addItem("Red"); colorList.addItem("Blue"); colorList.addItem("Green"); The items will be added to the list in the order addItem is executed. Then we execute selection = colorList.getSelectedIndex(); to make the colorList appear on the screen… 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
23
ListBox – Items in colorList
Chapter 6 ListBox – Items in colorList The variable selection is an int. When the user makes a selection by clicking on the choice and then clicking on the OK button, the getSelectedIndex method returns the index value of the selected choice. The choice at the top has the index value 0, the second from the top is 1, and so forth. Notice that the index of the first item in the list is zero, not one. Assigning zero to the first position is called zero-based indexing, which is used very frequently in computer programming. Zero-based indexing assigns the value of zero to the first item in a list of items. The getSelectedIndex method returns the index value of the selected choice. 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
24
Introduction to Object-Oriented Programming with Java--Wu
Chapter 6 ListBox Methods The getSelectedIndex method returns NO_SELECTION if the user clicks the OK button without selecting a choice, and it returns CANCEL if the user clicks the Cancel button or the close box. After the value is returned by the getSelectedIndex method, the ListBox disappears from the screen. NO_SELECTION and CANCEL are public class constants of type int, and we refer to them as ListBox.NO_SELECTION and ListBox.CANCEL 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
25
ListBox – Processing the User Selection (page 251)
Chapter 6 ListBox – Processing the User Selection (page 251) selection = colorList.getSelectedIndex(); if (selection == ListBox.NO_SELECTION) messageBox.show("You made no selection"); else if (selection == ListBox.CANCEL) messageBox.show("You canceled the ListBox"); else if (selection == 0) messageBox.show("You selected Magenta"); else if (selection == 3) messageBox.show("You selected Blue"); else if (selection == 4) messageBox.show("You selected Green"); The use of public constants NO_SELECTION and CANCEL makes the code more readable. It also makes the modification of code easier. The following is the complete if statement. if (selection == ListBox.NO_SELECTION) messageBox.show("You made no selection"); else if (selection == ListBox.CANCEL) messageBox.show("You canceled the ListBox"); else if (selection == 0) messageBox.show("You selected Magenta"); else if (selection == 1) messageBox.show("You selected Cyan"); else if (selection == 2) messageBox.show("You selected Red"); else if (selection == 3) messageBox.show("You selected Blue"); else if (selection == 4) messageBox.show("You selected Green"); Notice the use of public constants for more readable and easily modifiable code. 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
26
Introduction to Object-Oriented Programming with Java--Wu
The switch Statement int gradeLevel; gradeLevel = inputBox.getInteger("Grade (Frosh-1,Soph-2,...):" ); switch (gradeLevel) { case 1: outputBox.printLine("Go to the Gymnasium"); break; case 2: outputBox.printLine("Go to the Science Auditorium"); case 3: outputBox.printLine("Go to Harris Hall Rm A3"); case 4: outputBox.printLine("Go to Bolt Hall Rm 101"); } This statement is executed if the gradeLevel is equal to 1. This statement is executed if the gradeLevel is equal to 4. 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu
27
Syntax for the switch Statement
switch ( <arithmetic expression> ) { <case label 1> : <case body 1> … <case label n> : <case body n> } Arithmetic Expression switch ( gradeLevel ) { case 1: outputBox.printLine("Go to the Gymnasium"); break; case 2: outputBox.printLine("Go to the Science Auditorium"); case 3: outputBox.printLine("Go to Harris Hall Rm A3"); case 4: outputBox.printLine("Go to Bolt Hall Rm 101"); } Case Label Case Body 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu
28
switch With No break Statements
x = 10; false true N == 1 ? x = 20; x = 30; N == 2 ? N == 3 ? switch ( N ) { case 1: x = 10; case 2: x = 20; case 3: x = 30; } 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu
29
switch With break Statements
x = 10; false true N == 1 ? x = 20; x = 30; N == 2 ? N == 3 ? break; switch ( N ) { case 1: x = 10; break; case 2: x = 20; case 3: x = 30; } 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu
30
switch With the default Block
Chapter 6 switch With the default Block switch (ranking) { case 10: case 9: case 8: messageBox.show("Master"); break; case 7: case 6: messageBox.show("Journeyman"); case 5: case 4: messageBox.show("Apprentice"); default: messageBox.show("Input error: Invalid Data"); } We may include a default case that will always be executed if there is no matching case. For example, we can add a default case to print out an error message if any invalid value for ranking is entered. There can be at most one default case. Since the execution continues to the next statement if there is no matching case (and no default case is specified), it is safer to always include a default case. By placing some kind of output statement in the default case, we can detect an unexpected switch value. Such style of programming is characterized as defensive programming. The default case does not have to be placed as the last case, but we recommend you do so, in order to make the switch statement more readable. 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu Intro to OOP w/Java--Wu
31
Sample Program: Drawing Shapes
Problem Statement Write an application that will draw a geometric shape specified by the user. The user can specify the shape’s position, size, and color. The program can draw lines, rectangles, and circles in the colors magenta, cyan, red, blue, or green. Major Tasks Get the shape the user wants to draw. Get the color the user wants to use. Get the position and size of the selected shape. Draw the selected shape as specified 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu
32
Introduction to Object-Oriented Programming with Java--Wu
DrawShape – Design 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu
33
DrawShape – Object Diagram
5/6/2019 Introduction to Object-Oriented Programming with Java--Wu
34
Loan Calculator – Development Steps
Start with a program skeleton. Define the DrawShapeMain and the DrawShape classes. Add code to allow the user to select a shape. Add code to allow the user to select a color. Add code to allow the user to specify the size and location of the selected shape. Add code to draw the selected shape. Finalize the code by tying up loose ends. 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu
35
Introduction to Object-Oriented Programming with Java--Wu
Exercise #4 Page 282, #7 and #8 5/6/2019 Introduction to Object-Oriented Programming with Java--Wu
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.