Download Chapter 4 Introduction to Control Statements

Document related concepts
no text concepts found
Transcript
Chapter 4
Introduction to Control
Statements
Fundamentals of Java
Objectives



2
Use the increment and decrement operators.
Use standard math methods.
Use if and if-else statements to make
choices.
Fundamentals of Java
Objectives (cont.)



3
Use while and for loops to repeat a
process.
Construct appropriate conditions for control
statements using relational operators.
Detect and correct common loop errors.
Fundamentals of Java
Vocabulary






4
Control statements
Counter
Count-controlled loop
Entry-controlled loop
Flowchart
Infinite loop
Fundamentals of Java
Vocabulary (cont.)





5
Iteration
Off-by-one error
Overloading
Sentinel
Task-controlled loop
Fundamentals of Java
Additional Operators

Extended assignment operators
–
6
Assignment operator combined with
arithmetic and concatenation operators
Fundamentals of Java
Additional Operators (cont.)

Increment operator: ++
–

Decrement operator: -–
7
Increase value of operand by 1
Decrease value of operand by 1
Fundamentals of Java
Standard Classes and Methods:
The Math Class
Table 4-1: Seven methods in the Math class
8
Fundamentals of Java
Standard Classes and Methods:
The Math Class (cont.)

The two abs() methods are overloaded.
–

9
Overloaded: Multiple methods in the same class
with the same name
Using sqrt() method example:
Fundamentals of Java
Standard Classes and Methods:
The Math Class (cont.)

10
Math class methods example:
Fundamentals of Java
Standard Classes and Methods:
The Random Class

Random number generator: Returns
numbers chosen at random from a predesignated interval
Table 4-2: Methods in the Random class
11
Fundamentals of Java
A Visit to the Farm
12
Fundamentals of Java
The if and if-else Statements

13
Principal forms:
Fundamentals of Java
The if and if-else Statements
(cont.)

14
Additional forms:
Fundamentals of Java
The if and if-else Statements
(cont.)

Better to over-use braces than under-use
them
–

Condition of an if statement must be a
Boolean expression
–

15
Can help to eliminate logic errors
Evaluates to true or false
A flowchart can be used to illustrate the
behavior of if-else statements.
Fundamentals of Java
The if and if-else Statements
(cont.)
Figure 4-1: Flowcharts for the if and if-else statements
16
Fundamentals of Java
The if and if-else Statements
(cont.)

17
Examples of if statements:
Fundamentals of Java
The if and if-else Statements
(cont.)
Table 4-3: Relational operators
18
Fundamentals of Java
The if and if-else Statements
(cont.): Checking Input for Validity
Example 4.1: Computes the area of a circle if the
radius >= 0 or otherwise displays an error message
19
Fundamentals of Java
The while Statement

Provides a looping mechanism
–
20
Executes statements repeatedly for as long as
some condition remains true
Fundamentals of Java
The while Statement (cont.)
Figure 4-2: Flowchart for a while statement
21
Fundamentals of Java
The while Statement (cont.)
22

Example:

Counter-controlled loop:
–
cntr is the counter
–
Loop repeats a determined number of times
Fundamentals of Java
The while Statement (cont.)

Tracing: Track value of variables through
each iteration of the loop
Table 4-4: Trace of how variables change
on each iteration through a loop
23
Fundamentals of Java
The while Statement (cont.)

24
Counting backward:
Fundamentals of Java
The while Statement (cont.)

25
Task-controlled loop: Continues to
execute until some task is accomplished
Fundamentals of Java
The while Statement (cont.)

26
Common structure of a while loop:
Fundamentals of Java
The while Statement (cont.)
Example 4.2: Compute and display the factorial of n
27
Fundamentals of Java
The for statement


28
Combines counter initialization, condition test,
and update into a single expression
Easy to create count-controlled loops
Fundamentals of Java
The for statement (cont.)

29
Example:
Fundamentals of Java
The for statement (cont.)

30
Count-controlled input:
Fundamentals of Java
The for statement (cont.)

Better to declare the loop control variable
within the loop header
–
–
31
Only visible within the loop
Variable name can be reused later in other loops
Fundamentals of Java
The for statement (cont.)

Both for loops and while loops are entrycontrolled loops.
–

Condition tested at top of loop on each pass
Choosing a for loop versus a while loop is
often a matter of style.
–
for loop advantages:
 Can
declare loop control variable in header
 Initialization, condition, and update in one line of
code
32
Fundamentals of Java
Nested Control Statements and
the break Statement

33
Control statements may be nested.
Fundamentals of Java
Nested Control Statements and
the break Statement (cont.)

34
break statement: Prematurely end a loop
Fundamentals of Java
Nested Control Statements and
the break Statement (cont.)

35
Sentinel-controlled input: Continue a loop
until a sentinel variable has a specific value
Fundamentals of Java
Using Loops with Text Files

Advantages of using text files versus input
from a human user:
–
–
–

36
Data sets can be much larger.
Data input quickly, with less chance of error.
Data can be used repeatedly.
Data files can be created by hand in a text
editor or generated by a program.
Fundamentals of Java
Using Loops with Text Files (cont.)

Text file format:
–
–
If data is numerical, numbers must be separated
by white space.
Must be an end-of-file character


When an error occurs at run-time, the JVM
throws an exception.
–
37
Used by program to determine whether it is done
reading data
IOException thrown if error occurs during file
operations
Fundamentals of Java
Using Loops with Text Files (cont.)
38
Example 4.3: Computes and displays the average
of a file of floating-point numbers
Fundamentals of Java
Using Loops with Text Files (cont.)
Example 4.4: Inputs a text file of integers and
writes these to an output file without the zeroes
39
Fundamentals of Java
Errors in Loops



40
May occur in initializing statements,
terminating conditions, body statements, or
update statements
Initialization error: Failure to initialize or
initializes to incorrect value
Off-by-one error: Loop iterates one too
many or one too few times
Fundamentals of Java
Errors in Loops (cont.)

Infinite loop: Error in the terminating
condition
–


Errors in loop body affect whether the loop
completes its task correctly or at all.
Update error: Update statements in wrong
place may affect calculations
–
41
Loop never terminates
Failing to update at all results in an infinite loop.
Fundamentals of Java
Errors in Loops (cont.)

Effects of limited floating-point precision:
When using floating-point variables as loop
control variables, you must understand that
not all values can be represented.
–
42
Better not to use == or != in condition
statement under these conditions
Fundamentals of Java
Errors in Loops (cont.)

Debugging loops:
–
If an error is suspected, make sure that:
 Variables
are initialized before entering the loop
 The terminating condition stops the iterations
when the test variables have reached the
intended limit
 The statements in the body are correct
43
Fundamentals of Java
Errors in Loops (cont.)

Debugging loops (cont.):
–
If an error is suspected, make sure that:
 The
update statements are positioned correctly
and modify the test variables so that they
eventually pass the limits tested in the
terminating condition
44
Fundamentals of Java
Graphics and GUIs: I/O Dialog
Boxes and Loops

A convenient way to accept input from a user
is to pop up an input dialog box.
–
Use JOptionPane.showInputDialog().
Figure 4-4: Input dialog box
45
Fundamentals of Java
Graphics and GUIs: I/O Dialog
Boxes and Loops (cont.)

If expected input is a number, must use
Integer.parseInt() or
Double.parseDouble()

To output a message, use a message dialog
box.
–
46
JOptionPane.showMessageDialog(
anObserver, aString)
Fundamentals of Java
Graphics and GUIs: I/O Dialog
Boxes and Loops (cont.)
Example 4.5: CircleArea with dialog I/O
47
Fundamentals of Java
Graphics and GUIs: I/O Dialog
Boxes and Loops (cont.)
Figure 4.5: Dialog I/O user interface for the circle area program
48
Fundamentals of Java
Graphics and GUIs: I/O Dialog
Boxes and Loops (cont.)

Setting up multiple panels:
–

Setting the preferred size of a panel:
–
–
49
Can use a loop to initialize and install panels
Use JPanel class’s setPreferredSize()
method.
JFrame class’s pack() method will cause the
window to adjust its size to exactly fit the
preferred size of any contained panels.
Fundamentals of Java
Graphics and GUIs: I/O Dialog
Boxes and Loops (cont.)
50
Example 4-7: Color panel whose background is a
color provided by the client. A client-specified
preferred size is optional.
Fundamentals of Java
Design, Testing, and Debugging
Hints



51
Most errors involving selection statements
and loops are not syntax errors.
The presence or absence of the {} symbols
can seriously affect the logic of a selection
statement or loop.
When testing programs that use if or ifelse statements, use test data that forces
the program to exercise all logical branches.
Fundamentals of Java
Design, Testing, and Debugging
Hints (cont.)



52
Use an if-else statement rather than two
if statements when the alternative courses
of action are mutually exclusive.
When testing a loop, be sure to use limit
values as well as typical values.
Be sure to check entry conditions and exit
conditions for each loop.
Fundamentals of Java
Design, Testing, and Debugging
Hints (cont.)


53
For a loop with errors, use debugging output
statements to verify the values of the control
variable on each pass through the loop.
Text files are convenient to use when the
data set is large, when the same data set
must be used repeatedly with different
programs, and when these data must be
saved permanently.
Fundamentals of Java
Summary




54
Java has operators for extended assignment
and for increment and decrement.
The Math class provides several useful
methods, such as sqrt and abs.
The Random class allows you to generate
random integers and floating-point numbers.
if and if-else statements are used to
make one-way and two-way decisions.
Fundamentals of Java
Summary (cont.)



55
The comparison operators, such as ==, <=,
and >=, return Boolean values that can serve
as conditions for control statements.
The while loop allows the program to run a
set of statements repeatedly until a condition
becomes false.
The for loop is a more concise version of
the while loop.
Fundamentals of Java
Summary (cont.)



Other control statements, such as an if
statement, can be nested within loops.
A break statement can be used with an if
statement to terminate a loop early.
Many kinds of logic errors can occur in loops.
–
–
56
Off-by-one error
Infinite loop
Fundamentals of Java