Download presentation
Presentation is loading. Please wait.
Published byLoreen Summers Modified over 6 years ago
1
Java Programming: Guided Learning with Early Objects
Chapter 5 Control Structures II: Repetition
2
Objectives Learn about repetition (looping) control structures
Explore how to construct and use: Counter-controlled repetition structures Sentinel-controlled repetition structures Flag-controlled repetition structures EOF-controlled repetition structures Examine break statements in loops Java Programming: Guided Learning with Early Objects
3
Objectives (continued)
Discover how to form and use nested control structures Learn how to avoid bugs by avoiding patches Learn how to draw shapes using the class Graphics Learn how to use JtextAreas in a GUI Java Programming: Guided Learning with Early Objects
4
Why Is Repetition Needed?
Many situations in which it is necessary to repeat a set of statements Three looping (repetition) structures: while for do…while Allow repeating statements over and over until certain conditions are met Java Programming: Guided Learning with Early Objects
5
while Looping (Repetition) Structure
Syntax: while (logical expression) statement logical expression is called a loop condition statement may be simple or compound If logical expression evaluates to true the statement executes Java Programming: Guided Learning with Early Objects
6
while Looping (Repetition) Structure (continued)
Infinite loop: executes indefinitely Loop control variable must be initialized before executing the loop If semicolon is at the end of the loop, the action of the loop is empty or null Java Programming: Guided Learning with Early Objects
7
Figure 5-1 while loop Java Programming: Guided Learning with Early Objects
8
Designing while loops Body of while loop executes only when logical expression evaluates to true Typically, logical expression determines if loop control variable (LCV) satisfies condition LCV must be initialized before while loop Value of LCV must eventually make condition false Value of LCV updated in loop body counter = 0; while (counter < n) Java Programming: Guided Learning with Early Objects
9
Counter-Controlled while Loops
Number of loop iterations known in advance Assume n iterations Counter initialized to 0 before while statement Before executing loop body, counter compared to n If counter less than n, loop body executes Inside loop body, counter incremented Java Programming: Guided Learning with Early Objects
10
Sentinel-Controlled while Loops
Sentinel: special value that signals end of processing Read first item before entering while statement If item is not the sentinel, loop body executes Loop continues as long as sentinel value not encountered while (variable != sentinel) Java Programming: Guided Learning with Early Objects
11
Flag-Controlled while Loops
Uses a boolean variable to control loop The boolean variable is known as a flag Must eventually be set to true in loop body boolean found = false; while (!found) Java Programming: Guided Learning with Early Objects
12
EOF-Controlled while Loops
If data file is frequently altered, avoid using a sentinel value Sentinel might accidentally be erased Programmer may not know sentinel value EOF-controlled while loop depends on stream object used to input data Java Programming: Guided Learning with Early Objects
13
EOF-Controlled while Loops (continued)
Scanner object: static Scanner console; console = new Scanner(System.in); Method hasNext returns true if there is an input in the input stream Java Programming: Guided Learning with Early Objects
14
EOF-Controlled while Loops (continued)
Expression console.hasNext() acts as loop condition console acts as loop control variable Expression like console.nextInt() updates value of loop control variable while (console.hasNext()) Java Programming: Guided Learning with Early Objects
15
More on Expressions in while Statements
while loop may be controlled by single variable Logical expression in while statement may be complex while ((numGuess < 7) && (!guessRight)) Java Programming: Guided Learning with Early Objects
16
for Looping (Repetition) Structure
while loop general enough to implement all forms of repetitions for loop syntax: for (initial expr;logical expr;update expr) statement logical expr is the loop condition Java Programming: Guided Learning with Early Objects
17
for Looping (Repetition) Structure (continued)
All three expressions are for loop control expressions for loop body may contain simple or compound statements Java Programming: Guided Learning with Early Objects
18
Figure 5-3 for loop Java Programming: Guided Learning with Early Objects
19
for Looping (Repetition) Structure (continued)
Execution of for loop: initial expr executes logical expr evaluated If loop condition evaluates to true, execute statement Execute update statement Repeat until loop condition evaluates to false Java Programming: Guided Learning with Early Objects
20
for Looping (Repetition) Structure (continued)
Primarily used to implement counter-controlled loops Called counted or indexed Loop control variable declared within for statement After for loop executes, using loop control variable generates a syntax error Loop body does not execute if logical expr initially false Java Programming: Guided Learning with Early Objects
21
for Looping (Repetition) Structure (continued)
update expr should change value of loop control variable Semicolon at end of for statement makes the for loop null If logical expr omitted, it is assumed true Can omit all three statements: for (;;) Java Programming: Guided Learning with Early Objects
22
do…while Looping (Repetition) Structure
Syntax: do statement while (logical expr); statement may be simple or compound Compound statement enclosed in braces logical expr is the loop condition Java Programming: Guided Learning with Early Objects
23
Figure 5-4 do…while loop Java Programming: Guided Learning with Early Objects
24
do…while Looping (Repetition) Structure (continued)
statement executes first logical expr evaluated If logical expr true, statement executes again Loop body must contain statement that ultimately makes logical expr false Java Programming: Guided Learning with Early Objects
25
do…while Looping (Repetition) Structure (continued)
while and for loops have entry conditions May never execute do…while loop has exit condition Always executes at least once Pretest loop: loop condition evaluated before executing loop body Posttest loop: loop condition evaluated after executing loop body Useful for input validation Java Programming: Guided Learning with Early Objects
26
Choosing the Right Looping Structure
for loop: number of repetitions known in advance while loop: number of repetitions cannot be determined in advance do…while loop: number of repetitions not known, but must be at least one Java Programming: Guided Learning with Early Objects
27
Loops and the break Statement
break statement alters flow of program control In switch structure, provides immediate exit from structure Used in while, for, do…while loops to exit from structures before loop ends Java Programming: Guided Learning with Early Objects
28
Loops and the break Statement (continued)
Two purposes: Exit early from a loop Skip remainder of switch structure After break statement executes, loop terminates Remaining loop statements skipped Program continues at first statement after loop Java Programming: Guided Learning with Early Objects
29
Loops and the break Statement (continued)
Use of break statement eliminates certain boolean variables Should be used sparingly Java Programming: Guided Learning with Early Objects
30
Nested Control Structures
Nested for loops: for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { while loop nested in for loop: for (int i = 0; i <= 4; i++) { while (num != 999) { Nested while loops: while (inFile.hasNext()) { Java Programming: Guided Learning with Early Objects
31
Avoiding Bugs by Avoiding Patches
Software patch is code written on top of existing code to remedy deficiency in original code Better to correct original deficiency Patches represent poor programming practice Java Programming: Guided Learning with Early Objects
32
GUI Graphics and JTextAreas (Optional)
class Graphics contained in package java.awt Provides methods for drawing items on the screen Methods draw shapes, bitmap images Class contains methods to set properties such as font and color Java Programming: Guided Learning with Early Objects
33
GUI Graphics and JTextAreas (Optional) (continued)
Java coordinate system Identifies every point on the screen Origin: upper-left corner of GUI component Coordinates (0,0) Every coordinate pair has x-coordinate and y-coordinate x-coordinate specifies horizontal position y-coordinate specifies vertical position Java Programming: Guided Learning with Early Objects
34
Figure 5-5 Java’s coordinate system
Java Programming: Guided Learning with Early Objects
35
Figure 5-6 Chair and a table
Java Programming: Guided Learning with Early Objects
36
Figure 5-7 Coordinates of the lines that make up the chair and table
Java Programming: Guided Learning with Early Objects
37
GUI Graphics and JTextAreas (Optional) (continued)
Method drawLine takes coordinates as parameters Methods of class Graphics are abstract Cannot create an instance of the class class JFrame has method paint Draws Graphics object on a JFrame object Coordinate system starts from upper-left corner of the window and contains window title Java Programming: Guided Learning with Early Objects
38
GUI Graphics and JTextAreas (Optional) (continued)
JPanel: a container placed inside a JFrame object below title of window class JPanel has method paintComponent Draws Graphics objects on JPanel object public void paintComponent (Graphics g) Java Programming: Guided Learning with Early Objects
39
GUI Graphics and JTextAreas (Optional) (continued)
Use class Graphics without creating Graphics object Override paintComponent to draw chair and table super.paintComponent(g); Java Programming: Guided Learning with Early Objects
40
GUI Graphics and JTextAreas (Optional) (continued)
Create class ChairAndTable by extending class JPanel Definition of paintComponent inside ChairAndTable Method paintComponent executed when ChairAndTable instantiated Java Programming: Guided Learning with Early Objects
41
Figure 5-8 Output of the ChairAndTableTestProg program
Java Programming: Guided Learning with Early Objects
42
GUI Graphics and JTextAreas (Optional) (continued)
random method of class Math generates random number Used to generate random: Number of figures Color Width Height Shape Java Programming: Guided Learning with Early Objects
43
Figure 5-9 Sample run of OvalsAndRectsTestProg
Java Programming: Guided Learning with Early Objects
44
JTextArea class JTextField used to input or display a line of text
JTextField cannot handle multiple lines class JTextArea collects multiple lines of input, displays multiple lines of output JTextField and JTextArea derived from class JTextComponent JTextComponent is an abstract class Java Programming: Guided Learning with Early Objects
45
Table 5-3 Methods Inherited by the class JTextArea from the Parent class JTextComponent
Java Programming: Guided Learning with Early Objects
46
Summary Java has three repetition structures: while loops: while for
do…while while loops: Counter-controlled Sentinel-controlled Flag-controlled EOF-controlled Java Programming: Guided Learning with Early Objects
47
Summary (continued) Infinite loop never terminates
Loop conditions may be simple or complex while loop general enough to implement all forms of repetition for loop implements counter-controlled loops Control variable declared in loop statement Number of iterations known do…while loop executes statement before evaluating condition Java Programming: Guided Learning with Early Objects
48
Summary (continued) Pretest loops evaluate condition before executing loop body Posttest loops execute body then evaluate condition break statement used for two purposes: Exit early from loop Skip remainder of switch structure After executing break statement in loop, remaining loop statements skipped Java Programming: Guided Learning with Early Objects
49
Summary (continued) Control structures may be nested
Software patches are poor programming practice Better to fix original deficiency class Graphics provides methods for drawing items on the screen Java coordinate system origin in upper-left corner Java Programming: Guided Learning with Early Objects
50
Summary (continued) Abstract classes cannot be instantiated
class Graphics is abstract Pass Graphics object to paintComponent method in JPanel Method random in class Math generates random numbers JTextField inputs or displays single line of text JTextArea inputs or displays multiple lines of text Java Programming: Guided Learning with Early Objects
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.