Transcript slides
1
Chapter 4 - Control Structures
Part 1
Will not cover 4.14, Thinking About Objects: Identifying Class
Attributes
2003 Prentice Hall, Inc. All rights reserved.
2
4.2
Algorithms
• Algorithm
– A finite set of instructions that specify a sequence of
operations to be carried out in order to solve a specific
problem or class of problems
• Pseudocode
– Informal language for writing algorithms
– Not executed on computers
• Program control:
– Means specifying the order in which operations execute
– Java control structures are used to specify this order
2003 Prentice Hall, Inc. All rights reserved.
3
4.4
Control Structures
• Three control structures can specify order of
execution of program statements
– Sequential execution:
Program statements execute one after the other
– Selection structure:
Non-sequential execution; transfer of control
– Repetition structure:
Non-sequential execution; transfer of control
• Activity diagram (flowchart)
– Models the workflow
2003 Prentice Hall, Inc. All rights reserved.
4
add grade to total
Corresponding Java statement:
total = total + grade;
add 1 to counter
Corresponding Java statement:
counter = counter + 1;
Fig 4.1 Sequence structure activity diagram.
2003 Prentice Hall, Inc. All rights reserved.
5
Ja va Keyw ord s
abstract
assert
boolean
break
case
catch
char
class
default
do
double
else
final
finally float
for
implements import
instanceof int
long
native
new
package
protected public
return
short
strictfp
super
switch
synchronized
throw
throws
transient try
volatile
while
Keywords that are reserved, but not currently used
const
goto
Fig. 4.2 Ja va keyw o rd s.
2003 Prentice Hall, Inc. All rights reserved.
byte
continue
extends
if
interface
private
static
this
void
6
4.4
Control Structures
• Java default control structure provides sequential
execution.
• Java provides three selection structures
– if
– If…else
– switch
• Java provides three repetition structures
– while
– do…while
– do
• Each of these words is a Java keyword
2003 Prentice Hall, Inc. All rights reserved.
7
4.5
if Single-Selection Statement
• Single-entry/single-exit control structure
• Perform action only when condition is true
[grade >= 60]
print “Passed”
[grade < 60]
Fig 4.3 if single-selections statement activity diagram.
2003 Prentice Hall, Inc. All rights reserved.
8
4.6
if…else Selection Statement
• Perform action only when condition is true
• Perform different specified action when condition
is false
• Nested if…else selection structures
[grade < 60]
print “Failed”
[grade >= 60]
print “Passed”
Fig 4.4 if…else double-selections statement activity diagram.
2003 Prentice Hall, Inc. All rights reserved.
9
Conditional operator (?:)
• Can be used in place of an if…else statement
• Takes 3 operands (ternary) operator
• example conditional expression:
System.out.println (studentGrade >= 60 ? “Passed” : “Failed” );
if condition is true , the output will be Passed , otherwise it will
be Failed
studentGrade >= 60 ? “Passed” : “Failed”
Equivalent to
If (studentGrade >= 60 )
expression evaluates to the string “Passed”
else
expression evaluates to the string “Failed”
2003 Prentice Hall, Inc. All rights reserved.
10
while Repetition Statement
4.7
Repeat action while condition remains true
merge
decision
[product <= 1000]
double product value
[product > 1000]
Corresponding Java statement:
product = 2 * product;
Fig 4.5 while repetition statement activity diagram.
2003 Prentice Hall, Inc. All rights reserved.
11
Formulating Algorithms: Counter-Controlled Repetition
• Counter: Variable that controls number of times
set of statements executes
• Solution to the class-average problem.
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Input the next grade
Add the grade into the total
Add one to the grade counter
Set the class average to the total divided by ten
Print the class average
Fig. 4.6 Pseudocode algorithm that uses countercontrolled repetition to solve the class-average
problem.
2003 Prentice Hall, Inc. All rights reserved.
12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Fig. 4.7: Average1.java
// Class-average program with counter-controlled repetition.
import javax.swing.JOptionPane;
Declare variables;
gradeCounter is the counter
public class Average1 {
public
{
int
int
int
int
static void main( String args[] )
total;
gradeCounter;
grade;
average;
//
//
//
//
sum of grades input by user
number of grade to be entered next
grade value
average of grades Continue looping
String gradeString; // grade typed by
Outline
Average1.java
gradeCounter
Line 21
as long as
gradeCounter is less than or
user
equal to 10
// initialization phase
total = 0;
// initialize total
gradeCounter = 1;
// initialize loop counter
// processing phase
while ( gradeCounter <= 10 ) {
// loop 10 times
// prompt for input and read grade from user
gradeString = JOptionPane.showInputDialog(
"Enter integer grade: " );
// convert gradeString to int
grade = Integer.parseInt( gradeString );
2003 Prentice Hall, Inc.
All rights reserved.
13
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
total = total + grade;
gradeCounter = gradeCounter + 1;
// add grade to total
// increment counter
} // end while
Outline
Average1.java
// termination phase
average = total / 10;
// integer division
// display average of exam grades
JOptionPane.showMessageDialog( null, "Class average is " + average,
"Class Average", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate the program
} // end main
} // end class Average1
2003 Prentice Hall, Inc.
All rights reserved.
14
Outline
Average1.java
2003 Prentice Hall, Inc.
All rights reserved.
Formulating Algorithms with Top-Down, Stepwise
Refinement:
Sentinel-Controlled Repetition
Develop a class averaging program that processes grades
for an arbitrary number of students each time the program
is run.
Top-Down, Stepwise Refinement Technique:
Top
a single statement conveys the overall function of
the program.
Determine the class average of the quiz
2003 Prentice Hall, Inc. All rights reserved.
15
16
First refinement
Initialize variables
Input, sum and count quiz grades
Calculate and print the class average
2003 Prentice Hall, Inc. All rights reserved.
Second refinement
Initialize variables:
Initialize total to zero
Initialize counter to zero
Input, sum and count quiz grades:
(Sentinel value: Input data item which used to indicated the end of data entry)
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
2003 Prentice Hall, Inc. All rights reserved.
17
18
Second refinement (continued)
Calculate and print the class average
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
else
Print “No grades were entered”
2003 Prentice Hall, Inc. All rights reserved.
Sentinel-Controlled Repetition
Initialize total to zero
Initialize counter to zero
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
else
Print “No grades were entered”
Fig. 4.8 Class-average problem pseudocode
algorithm with sentinel-controlled repetition.
• Average2.java has indefinite repetition
– User enters sentinel value (-1) to end repetition
2003 Prentice Hall, Inc. All rights reserved.
19
20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Fig. 4.9: Average2.java
// Class-average program with sentinel-controlled repetition.
import java.text.DecimalFormat; // class to format numbers
import javax.swing.JOptionPane;
Outline
Average2.java
public class Average2 {
public static void main( String args[] )
{
int total;
// sum of grades
int gradeCounter;
// number of grades entered
int grade;
// grade value
double average;
// number with decimal point for average
String gradeString;
// grade typed by user
// initialization phase
total = 0;
// initialize total
gradeCounter = 0; // initialize loop counter
// processing phase
// get first grade from user
gradeString = JOptionPane.showInputDialog(
"Enter Integer Grade or -1 to Quit:" );
// convert gradeString to int
grade = Integer.parseInt( gradeString );
2003 Prentice Hall, Inc.
All rights reserved.
21
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// loop until sentinel value read from user
while ( grade != -1 ) {
until grade
total = total + grade;
// loop
add grade
to totalequals
gradeCounter = gradeCounter + 1; // increment
sentinelcounter
value (-1)
// get next grade from user
gradeString = JOptionPane.showInputDialog(
"Enter Integer Grade or -1 to Quit:" );
// convert gradeString to int
Format numbers to nearest
grade = Integer.parseInt( gradeString
); more on line 45 later
hundredth;
Outline
Average2.java
Line 31
Line 45
} // end while
// termination phase
DecimalFormat twoDigits = new DecimalFormat( "0.00" );
// if user entered at least one grade...
if ( gradeCounter != 0 ) {
//calculate average, cast operator (double), gradeCounter promoted
average = (double) total / gradeCounter;
double: cast
// display average with two digits of precision
operator ;
JOptionPane.showMessageDialog( null,
gradeCount
"Class average is " + twoDigits.format( average ),
er promoted
"Class Average", JOptionPane.INFORMATION_MESSAGE );
} // end if part of if...else
2003 Prentice Hall, Inc.
All rights reserved.
22
60
61
62
63
64
65
66
67
68
else // if no grades entered, output appropriate message
JOptionPane.showMessageDialog( null, "No grades were entered",
"Class Average", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
Outline
Average2.java
} // end main
} // end class Average2
2003 Prentice Hall, Inc.
All rights reserved.
45
DecimalFormat twoDigits = new DecimalFormat( "0.00" );
• Declares twoDigits a reference to an object of class
DecimalFormat
• Creates a DecimalFormat object initialized with the
pattern “0.00”
• Every number formatted with twoDigits will have at
least one digit to the left of decimal point and two
decimal digits
• new : an operator that creates an object of the type
specified and initialized by the constructor to the
right of new, DecimalFormat( "0.00" )
• twoDigits gets the value of new DecimalFormat(
"0.00" )
2003 Prentice Hall, Inc. All rights reserved.
23
24
Analysis of Grades Problem
• Develop a class analyzing program that processes 10
grades and recommends raising tuition if more than 8
students passed the exam.
2003 Prentice Hall, Inc. All rights reserved.
Formulating Algorithms with Top-Down, Stepwise
Refinement:Nested Control Structures
25
Initialize passes to zero
Initialize failures to zero
Initialize student to one
While student counter is less than or equal to ten
Input the next exam result
If the student passed
Add one to passes
else
Add one to failures
If structure is nested
inside the while structure
Add one to student counter
Print the number of passes
Print the number of failures
If more than eight students passed
Print “Raise tuition”
Fig 4.10 Pseudocode for examination-results problem.
2003 Prentice Hall, Inc. All rights reserved.
26
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Outline
// Fig. 4.11: Analysis.java
// Analysis of examination results.
import javax.swing.JOptionPane;
public class Analysis {
Loop until student counter is
greater than 10
public static void main( String args[] )
{
// initializing variables in declarations
int passes = 0;
// number of passes
int failures = 0;
// number of failures
int studentCounter = 1; // student counter
int result;
// one exam result
String input;
String output;
Analysis.java
Line 19
Line 29
// user-entered value
// output string
// process 10 students using counter-controlled loop
while ( studentCounter <= 10 ) {
Nested control structure
// prompt user for input and obtain value from user
input = JOptionPane.showInputDialog(
"Enter result (1 = pass, 2 = fail)" );
// convert result to int
result = Integer.parseInt( input );
// if result 1, increment passes; if...else nested in while
if ( result == 1 )
passes = passes + 1;
2003 Prentice Hall, Inc.
All rights reserved.
27
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
else // if result not 1, increment failures
failures = failures + 1;
// increment studentCounter so loop eventually terminates
studentCounter = studentCounter + 1;
Outline
Analysis.java
} // end while
// termination phase; prepare and display results
output = "Passed: " + passes + "\nFailed: " + failures;
// determine whether more than 8 students passed
if ( passes > 8 )
output = output + "\nRaise Tuition";
JOptionPane.showMessageDialog( null, output,
"Analysis of Examination Results",
JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
// terminate application
} // end main
} // end class Analysis
2003 Prentice Hall, Inc.
All rights reserved.
28
4.11 Compound Assignment Operators
c = c + 3
can be written as
c += 3
+= is a example “Compound Assignment
Operator”
2003 Prentice Hall, Inc. All rights reserved.
29
Assignment
Sample
Explanation
operator
expression
Assume: int c = 3,
d = 5, e = 4, f
= 6, g = 12;
+=
c += 7
c = c + 7
-=
d -= 4
d = d - 4
*=
e *= 5
e = e * 5
/=
f /= 3
f = f / 3
%=
g %= 9
g = g % 9
Fig. 4.12 Compound arithmetic assignment operators.
2003 Prentice Hall, Inc. All rights reserved.
Assigns
10 to c
1 to d
20 to e
2 to f
3 to g
30
Op era tor Ca lled
++
preincrement
++
postincrement
--
predecrement
--
postdecrement
Fig. 4.13 The inc rem ent
2003 Prentice Hall, Inc. All rights reserved.
Sa m p le
exp ression
++a
Exp la na tion
Increment a by 1, then use the new
value of a in the expression in
which a resides.
a++
Use the current value of a in the
expression in which a resides, then
increment a by 1.
--b
Decrement b by 1, then use the
new value of b in the expression in
which b resides.
b-Use the current value of b in the
expression in which b resides, then
decrement b by 1.
a nd d ec re m ent op era tors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
31
// Fig. 4.14: Increment.java
// Preincrementing and postincrementing operators.
public class Increment {
Outline
Line 13 postincrements c
public static void main( String args[] )
{
int c;
// demonstrate postincrement
c = 5;
//
System.out.println( c );
//
System.out.println( c++ ); //
System.out.println( c );
//
System.out.println();
assign 5 to c
print 5
Line postincrement
21 preincrements
print 5 then
print 6
Increment.java
Line 13 postincrement
Line 21 preincrement
c
// skip a line
// demonstrate preincrement
c = 5;
//
System.out.println( c );
//
System.out.println( ++c ); //
System.out.println( c );
//
assign 5 to c
print 5
preincrement then print 6
print 6
} // end main
} // end class Increment
5
5
6
5
6
6
2003 Prentice Hall, Inc.
All rights reserved.
32
Op era tors
Assoc ia tivity
Typ e
++ -right to left
unary postfix
++ -- +
(type)
right to left
unary
*
/
%
left to right
multiplicative
+
left to right
additive
<
<= >
>=
left to right
relational
== !=
left to right
equality
?:
right to left
conditional
=
+= -= *= /= %=
right to left
assignment
Fig. 4.15 Prec ed enc e a nd a ssoc ia tivity of the op era tors d isc ussed so fa r.
Operators ae shown from top to bottom in decreasing order of precedence
2003 Prentice Hall, Inc. All rights reserved.
33
Assume: int c = 3, d = 5, e = 4, f = 6, g
= 12;
c += 7 * e++ +g / d –-e % f
2003 Prentice Hall, Inc. All rights reserved.
? to c
34
4.13 Primitive Types
• Primitive types
– “building blocks” for more complicated types
• Java is strongly typed
– All variables in a Java program must have a type
• Java primitive types
– portable across computer platforms that support Java
2003 Prentice Hall, Inc. All rights reserved.
35
Typ e
boolean
Size in b its
char
16
byte
8
short
16
int
32
long
64
float
32
double
64
Fig. 4.16 The Ja va
Va lues
true or false
Sta nd a rd
[Note: The representation of a boolean is
specific to the Java Virtual Machine on each
computer platform.]
'\u0000' to '\uFFFF'
(ISO Unicode character set)
(0 to 65535)
–128 to +127
(–27 to 27 – 1)
–32,768 to +32,767
(–215 to 215 – 1)
–2,147,483,648 to +2,147,483,647
(–231 to 231 – 1)
–9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
(–263 to 263 – 1)
Negative range:
(IEEE 754 floating point)
–3.4028234663852886E+38 to
–1.40129846432481707e–45
Positive range:
1.40129846432481707e–45 to
3.4028234663852886E+38
Negative range:
(IEEE 754 floating point)
–1.7976931348623157E+308 to
–4.94065645841246544e–324
Positive range:
4.94065645841246544e–324 to
1.7976931348623157E+308
p rim itive typ es.
2003 Prentice Hall, Inc. All rights reserved.