Download presentation
Presentation is loading. Please wait.
Published byAshlie Joleen Rich Modified over 6 years ago
1
Java Programming: Guided Learning with Early Objects
Chapter 4 Control Structures I: Selection
2
Objectives Learn control structures
Examine relational and logical operators Explore how to form and evaluate logical (Boolean) expressions Learn how to use the selection control structures if, if…else, and switch in a program Java Programming: Guided Learning with Early Objects
3
Objectives (continued)
Learn how to avoid bugs by avoiding partially understood concepts and techniques Learn about JTextFields and JPanels Java Programming: Guided Learning with Early Objects
4
Control Structures Four ways a computer processes statements:
Sequentially Selection Repetition Method calls Branching: alter execution flow by selection Looping: alter execution flow by repetition Java Programming: Guided Learning with Early Objects
5
Figure 4-1 Flow of execution examples: (a) sequential, (b) selection, (c) repetition
Java Programming: Guided Learning with Early Objects
6
Relational Operators Express conditions
Make comparisons to make decisions Logical (Boolean) expression: has a value of either true or false Relational operator: allows comparisons in a program Relational operators are binary Binary operators require two operands Result of comparison is true or false Java Programming: Guided Learning with Early Objects
7
Table 4-1 Relational Operators in Java
Java Programming: Guided Learning with Early Objects
8
Relational Operators and Primitive Data Types
Relational operators used with integral and floating-point data types Expression Meaning Value 8 < 15 8 less than 15 True 6 != 6 6 not equal to 6 False 2.5 > 5.8 2.5 greater than 5.8 5.9 <= 7.5 5.9 less than or equal to 7.5 true Java Programming: Guided Learning with Early Objects
9
Comparing Floating-Point Numbers for Equality
Check absolute value of difference of two floating-point numbers Difference less than given tolerance Use method abs from class Math Example: Math.abs(x – y) < Java Programming: Guided Learning with Early Objects
10
Comparing Characters Expression using relational operators evaluates to true or false based on collating sequence Example: ‘R’ > ‘T’ Java Programming: Guided Learning with Early Objects
11
Table 4-2 Evaluating Expressions Using Relational Operators and the Unicode (ASCII) Collating Sequence Java Programming: Guided Learning with Early Objects
12
Comparing Strings Strings compared character by character
Comparison continues until: Mismatch found Last characters compared and are equal One string exhausted Shorter string less than larger string if comparison equal through shorter string Use method compareTo of class String Java Programming: Guided Learning with Early Objects
13
Strings, the Assignment Operator, and the Operator new
Example 1: String str1 = “Hello”; String str2 = “Hello”; (str1 == str2) evaluates to true str1.equals(str2) evaluates to true Example 2: String str3 = new String(“Hello”); String str4 = new String(“Hello”); (str3 == str4) evaluates to false str3.equals(str4) evaluates to true Java Programming: Guided Learning with Early Objects
14
Figure 4-3 Variables str1, str2, and the objects they point to
Java Programming: Guided Learning with Early Objects
15
Figure 4-4 Variables str3, str4, and the objects they point to
Java Programming: Guided Learning with Early Objects
16
Wrapper Classes (Revisited)
Use method compareTo to compare values of two Integer objects Use method equals to compare values of two Integer objects for equality Relational operators compare values of Integer and Double objects Using autoboxing and auto-unboxing Assignment operator always uses operator new to create Double object Java Programming: Guided Learning with Early Objects
17
Logical (Boolean) Operators and Logical Expressions
Logical (Boolean) operators enable you to combine logical expressions Logical operators take logical values as operands Binary operators: && and || Unary operator: ! Java Programming: Guided Learning with Early Objects
18
Table 4-6 && (and) Operator
Table 4-7 || (or) Operator Java Programming: Guided Learning with Early Objects
19
Order of Precedence Expression might contain arithmetic, relational, and logical operators Relational and logical operators evaluated left to right Left-to-right associativity Parentheses clarify meaning, override precedence of operators Java Programming: Guided Learning with Early Objects
20
Table 4-8 Precedence of Operators
Java Programming: Guided Learning with Early Objects
21
Short-Circuit Evaluation
Logical expressions evaluated using efficient algorithm Short-circuit evaluation: Logical expression evaluated left to right Stops when value of entire expression known Java Programming: Guided Learning with Early Objects
22
boolean Data Type and Logical (Boolean) Expressions
boolean data type has values true and false Logical expressions manipulated using boolean data type boolean, true, false are reserved words Java Programming: Guided Learning with Early Objects
23
Selection: if and if…else
Logical values permit programs to incorporate decision-making Alters processing flow Three selection or branch control structures: if if…else switch Java Programming: Guided Learning with Early Objects
24
One-Way Selection One-way selection syntax: if (logical expression)
statement logical expression also called condition Determines whether to execute statement If expression true, statement executes statement also called action statement Java Programming: Guided Learning with Early Objects
25
Figure 4-5 One-way selection
Java Programming: Guided Learning with Early Objects
26
Two-Way Selection May need to choose between two alternatives
Java provides if…else statement Two-way selection syntax: if (logical expression) statement1 else statement2 If logical expression is true, statement1 executes Otherwise statement2 executes Java Programming: Guided Learning with Early Objects
27
Figure 4-7 Two-way selection
Java Programming: Guided Learning with Early Objects
28
Compound (Block of) Statements
if and if…else structures select one statement at a time Compound statement (block) permits more complex statements Syntax: { statement1 statement2 … statementn } Java Programming: Guided Learning with Early Objects
29
Multiple Selections: Nested if
Some problems require implementation of more than two alternatives Include multiple selection paths using nested control statements Java associates else with the most recent incomplete if Java Programming: Guided Learning with Early Objects
30
Comparing if…else Statements with a Series of if Statements
a. if (month == 1) System.out.println(“January”); else if (month == 2) System.out.println(“February”); else if (month == 3) System.out.println(“March”); b. if (month == 1) if (month == 2) if (month == 3) Example a executes faster than b Java Programming: Guided Learning with Early Objects
31
Conditional Operator (? :) (Optional)
Conditional operator written as ?: Ternary operator Syntax: expr1 ? expr2 : expr3 Performs an evaluation and returns a value Example: max = (a >= b) ? a : b; Java Programming: Guided Learning with Early Objects
32
switch Structures switch structure does not require evaluation of logical expression: switch (expr) { case val1: statements1 break; case val2: statements2 default: statements } Java Programming: Guided Learning with Early Objects
33
Figure 4-8 switch statement
Java Programming: Guided Learning with Early Objects
34
switch Structures (continued)
switch statement executes according to value of expression matched against a case label Statements execute until break statement or end of structure If value of expression does not match case labels, default label executes If no default statements, structure skipped break statement causes exit from switch structure If no break statement, execution continues Java Programming: Guided Learning with Early Objects
35
Choosing Between an if…else and a switch Structure
No fixed rules to decide whether to use if…else or switch If multiple selections involve a range of values: Use either if…else or switch structure Convert each range to a distinct value If range of values is large and cannot be reduced: Use if..else structure Java Programming: Guided Learning with Early Objects
36
Avoiding Bugs by Avoiding Partially Understood Concepts and Techniques
Not sufficient to be mostly correct in use of concepts and techniques Many ways to solve a problem Must make correct use of concepts and techniques Do not use a concept or technique until understanding is complete Learn concepts one at a time in a logical order Take time to understand each one Java Programming: Guided Learning with Early Objects
37
Thermometer Class (Revisited)
class Thermometer provides current, maximum, minimum temperature for the day Before method definition, include comments specifying preconditions and postconditions Precondition: statement specifying conditions that must be true before method called Postcondition: statement specifying what is true after method call completed Java Programming: Guided Learning with Early Objects
38
GUI JTextFields and JPanels (Optional)
Display all input and output Text fields: white areas to the right of labels After entering the radius User clicks Calculate button Program calculates and displays the area and circumference User clicks Exit button, program terminates Java Programming: Guided Learning with Early Objects
39
Figure 4-9 GUI to find and display the circumference and area of a circle
Java Programming: Guided Learning with Early Objects
40
JTextField Text field objects belong to class JTextField
Instantiate an object of type JTextField JTextField used for both input and output Complete the design: Create three labels Create two buttons Calculate and Exit Place labels, text fields, buttons in content pane Set title of window, height, width Make window visible Java Programming: Guided Learning with Early Objects
41
Handling the Events Clicking buttons will generate an event
Must write code to handle each event and register listeners class CalculateButtonHandler and class ExitButtonHandler inner classes Inside class CircleProgram Method main instantiates single object of class CircleProgram Java Programming: Guided Learning with Early Objects
42
Figure 4-10 Sample run for the final CircleProgram
Java Programming: Guided Learning with Early Objects
43
JPanel Sometimes want to vary the number of components in each row
Set layout of container to null Specify position of components Use class JPanel JPanel objects are containers Create panels and subpanels Specify layout of each panel Subpanels added to panel below Panels added to content pane Java Programming: Guided Learning with Early Objects
44
Handling the Events Clicking buttons generates action event
One inner class handles all three events public void actionPerformed(ActionEvent e) Parameter e identifies source of event Use method getActionCommand of class ActionEvent Returns command associated with action String str = e.getActionCommand(); Java Programming: Guided Learning with Early Objects
45
Figure 4-12 Graphical user interface after entering the text
Figure 4-13 Graphical user interface after clicking the three buttons Java Programming: Guided Learning with Early Objects
46
Summary Program statements processed in four ways:
Sequentially Selection (branching) Repetition (looping) Method calls Logical expression has value of true or false Also called Boolean expression Relational operator makes comparisons Floating-point numbers compared, given tolerance Java Programming: Guided Learning with Early Objects
47
Summary (continued) char values compared using collating sequence
Strings compared character by character class String provides compareTo method Strings instantiated with assignment statement Strings instantiated with new operator Integers compared for equality using: equals method compareTo Java Programming: Guided Learning with Early Objects
48
Summary (continued) Assignment operator always uses operator new to create Double object Logical (Boolean) operators allow combining logical expressions Relational and logical operators left-to-right associative Java logical expressions use short-circuit evaluation One-way selection: if Java Programming: Guided Learning with Early Objects
49
Summary (continued) Two-way selection: if…else
Compound statements allow more than one statement to execute in selection structure Selection structures may be nested to allow multiple selection Conditional operator more concise form of if…else statement switch structure does not require evaluation of logical expression Java Programming: Guided Learning with Early Objects
50
Summary (continued) Learn concepts one at a time in logical order
JTextField used for input and output JPanel objects are containers Create a hierarchy of JPanels One handler can handle multiple events Use parameter e of type ActionEvent Use method getActionCommand of class ActionEvent Java Programming: Guided Learning with Early Objects
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.