Java Program Control Repetition - Department of Computer and
Download
Report
Transcript Java Program Control Repetition - Department of Computer and
Department of Computer and Information Science,
School of Science, IUPUI
Program Control using Java
- Repetition
Dale Roberts, Lecturer
Computer Science, IUPUI
E-mail: [email protected]
Dale Roberts
while Repetition Statement
while statement
Repeats an action while its loop-continuation condition
remains true
Uses a merge symbol in its UML activity diagram
Merges two or more workflows
Represented by a diamond (like decision symbols) but has:
Multiple incoming transition arrows,
Only one outgoing transition arrow and
No guard conditions on any transition arrows
2
Dale Roberts
Fig. 4.4 | while repetition statement UML activity diagram.
3
Dale Roberts
Formulating Algorithms: Counter-Controlled Repetition
Counter-controlled repetition
Use a counter variable to count the number of times a
loop is iterated
Integer division
The fractional part of an integer division calculation is
truncated (thrown away)
4
Dale Roberts
1
2
3
4
5
6
7
8
9
10
11
Set total to zero
Set grade counter to one
While grade counter is less than or equal to ten
Prompt the user to enter the next grade
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.5 | Pseudocode algorithm that uses counter-controlled repetition to
solve the class-average problem.
5
Dale Roberts
1
// Fig. 4.6: GradeBook.java
2
// GradeBook class that solves class-average problem using
3
// counter-controlled repetition.
4
import java.util.Scanner; // program uses class Scanner
Outline
6
5
6
public class GradeBook
7
{
8
private String courseName; // name of course this GradeBook represents
•GradeBook.java
(1 of 3)
9
10
// constructor initializes courseName
11
public GradeBook( String name )
12
{
courseName = name; // initializes courseName
13
14
} // end constructor
Assign a value to instance variable courseName
15
16
// method to set the course name
17
public void setCourseName( String name )
18
{
courseName = name; // store the course name
19
20
Declare method setCourseName
} // end method setCourseName
21
22
// method to retrieve the course name
23
public String getCourseName()
24
{
25
26
return courseName;
Declare method getCourseName
} // end method getCourseName
27
Dale Roberts
28
// display a welcome message to the GradeBook user
29
public void displayMessage()
30
{
Outline
Declare method displayMessage
31
// getCourseName gets the name of the course
32
System.out.printf( "Welcome to the grade book for\n%s!\n\n",
33
getCourseName() );
34
} // end method displayMessage
•GradeBook.java
(2 of 3)
35
36
// determine class average based on 10 grades entered by user
37
public void determineClassAverage()
38
{
39
// create Scanner to obtain input from command window
40
Scanner input = new Scanner( System.in );
41
Declare method determineClassAverage
42
int total; // sum of grades entered by user
43
int gradeCounter; // number of the grade to be entered next
44
int grade; // grade value entered by user
45
int average; // average of grades
Declare and initialize Scanner
variable input
46
Declare local int variables total,
gradeCounter, grade and average
47
// initialization phase
48
total = 0; // initialize total
49
gradeCounter = 1; // initialize loop counter
50
Dale Roberts
7
51
// processing phase
52
while ( gradeCounter <= 10 ) // loop 10 times
53
{
Outline
while loop iterates as long as
gradeCounter <= 10
54
System.out.print( "Enter grade: " ); // prompt
55
grade = input.nextInt(); // input next grade
56
total = total + grade; // add grade to total
57
gradeCounter = gradeCounter + 1; // increment counter by 1
58
} // end while
59
Increment the counter variable gradeCounter
60
// termination phase
61
average = total / 10; // integer division yields integer result
62
Calculate average grade
63
// display total and average of grades
64
System.out.printf( "\nTotal of all 10 grades is %d\n", total );
65
System.out.printf( "Class average is %d\n", average );
66
} // end method determineClassAverage
67
68 } // end class GradeBook
Display results
Dale Roberts
•GradeBook.java
(3 of 3)
8
Common Programming Error
Using the value of a local variable
before it is initialized results in a
compilation error. All local
variables must be initialized before
their values are used in
expressions.
Java initializes all variables to 0 by
default.
9
Dale Roberts
Common Programming Error
Not providing, in the body of a while
statement, an action that eventually
causes the condition in the while to
become false normally results in a
logic error called an infinite loop, in
which the loop never terminates.
10
Dale Roberts
1
// Fig. 4.7: GradeBookTest.java
2
// Create GradeBook object and invoke its determineClassAverage method.
Outline
3
4
public class GradeBookTest
5
{
6
public static void main( String args[] )
7
{
Create a new GradeBook object
8
// create GradeBook object myGradeBook and
9
// pass course name to constructor
10
GradeBook myGradeBook = new GradeBook(
"CS101 Introduction to Java Programming" );
11
12
Pass the course’s name to the GradeBook
constructor as a string
13
myGradeBook.displayMessage(); // display welcome message
14
myGradeBook.determineClassAverage(); // find average of 10 grades
15
•GradeBook
Test.java
} // end main
16
17 } // end class GradeBookTest
Welcome to the grade book for
CS101 Introduction to Java Programming!
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
grade:
grade:
grade:
grade:
grade:
grade:
grade:
grade:
grade:
grade:
Call GradeBook’s
determineClassAverage method
67
78
89
67
87
98
93
85
82
100
Total of all 10 grades is 846
Class average is 84
11
Dale Roberts
Formulating Algorithms: Sentinel-Controlled Repetition
Sentinel-controlled repetition
Also known as indefinite repetition
Use a sentinel value (also known as a signal, dummy or
flag value)
A sentinel value cannot also be a valid input value
12
Dale Roberts
Common Programming Error 4.6
Choosing a sentinel value that is
also a legitimate data value is a
logic error.
13
Dale Roberts
Fig. 5.3 | for statement header components.
14
Dale Roberts
UML activity diagram for the for statement in Fig. 5.2.
15
Dale Roberts
5.3 for Repetition Statement (Cont.)
for ( initialization; loopContinuationCondition; increment )
statement;
can usually be rewritten as:
initialization;
while ( loopContinuationCondition )
{
statement;
increment;
}
16
Dale Roberts
5.4 Examples Using the for Statement
Varying control variable in for statement
Vary control variable from 1 to 100 in increments of 1
for ( int i = 1; i <= 100; i++ )
Vary control variable from 100 to 1 in increments of –1
for ( int i = 100; i >= 1; i-- )
Vary control variable from 7 to 77 in increments of 7
for ( int i = 7; i <= 77; i += 7 )
Vary control variable from 20 to 2 in decrements of 2
for ( int i = 20; i >= 2; i -= 2 )
Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20
for ( int i = 2; i <= 20; i += 3 )
Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33,
22, 11, 0
for ( int i = 99; i >= 0; i -= 11 )
17
Dale Roberts
1
// Fig. 5.7: DoWhileTest.java
2
3
// do...while repetition statement.
4
public class DoWhileTest
5
6
7
8
9
{
Outline
18
public static void main( String args[] )
{
int counter = 1; // initialize counter
Declares and initializes
control variable counter
Variable counter’s value is displayed
before testing counter’s final value
10
do
11
12
13
{
14
15
16
} while ( counter <= 10 ); // end do...while
System.out.printf( "%d
++counter;
", counter );
System.out.println(); // outputs a newline
17
} // end main
18 } // end class DoWhileTest
1
2
3
4
5
6
7
8
9
10
Dale Roberts
DoWhile
Test.jav
a
Line 8
Lines
10-14
Progra
m
output
Fig. 5.8 | do...while repetition statement UML activity
diagram.
19
Dale Roberts
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
// Fig. 5.9: GradeBook.java
// GradeBook class uses switch statement to count A, B, C, D and F grades.
import java.util.Scanner; // program uses class Scanner
public class GradeBook
{
private String courseName; // name of course this GradeBook represents
private int total; // sum of grades
private int gradeCounter; // number of grades entered
private int aCount; // count of A grades
private int bCount; // count of B grades
private int cCount; // count of C grades
private int dCount; // count of D grades
private int fCount; // count of F grades
// constructor initializes courseName;
// int instance variables are initialized to 0 by default
public GradeBook( String name )
{
courseName = name; // initializes courseName
} // end constructor
// method to set the course name
public void setCourseName( String name )
{
courseName = name; // store the course name
} // end method setCourseName
Dale Roberts
Outline
20
GradeB
ook.java
(1 of 5)
Lines 8-14
29
// method to retrieve the course name
30
public String getCourseName()
31
{
32
33
return courseName;
} // end method getCourseName
34
35
36
37
38
39
40
// display a welcome message to the GradeBook user
public void displayMessage()
{
// getCourseName gets the name of the course
System.out.printf( "Welcome to the grade book for\n%s!\n\n",
getCourseName() );
41
42
43
} // end method displayMessage
44
45
public void inputGrades()
{
46
47
48
49
50
51
52
53
54
Outline
21
GradeB
ook.java
(2 of 5)
Lines 50-54
// input arbitrary number of grades from user
Scanner input = new Scanner( System.in );
Display prompt
int grade; // grade entered by user
System.out.printf( "%s\n%s\n
%s\n
%s\n",
"Enter the integer grades in the range 0-100.",
"Type the end-of-file indicator to terminate input:",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <ctrl> z then press Enter" );
55
Dale Roberts
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// loop until user enters the end-of-file indicator
while ( input.hasNext() )
{
grade = input.nextInt(); // read grade
total += grade; // add grade to total Loop condition uses method hasNext to
++gradeCounter; // increment numberdetermine
of grades whether there is more data to input
Outline
// call method to increment appropriate counter
incrementLetterGradeCounter( grade );
} // end while
} // end method inputGrades
// add 1 to appropriate counter for specified grade
public void incrementLetterGradeCounter( int numericGrade )
{
(grade / 10 ) is controlling
// determine which grade was entered
switch ( grade / 10 )
expression
{
case 9: // grade was between 90
switch statement determines which
case 10: // and 100
case label to execute, depending on
++aCount; // increment aCount
controlling expression
break; // necessary to exit switch
case 8: // grade was between 80 and 89
++bCount; // increment bCount
break; // exit switch
Dale Roberts
22
GradeB
ook.java
(3 of 5)
Line 57
Line 72
controlling
expression
Lines 72-94
case 7: // grade was between 70 and 79
83
Outline
++cCount; // increment cCount
break; // exit switch
84
85
86
87
23
case 6: // grade was between 60 and 69
++dCount; // increment dCount
break; // exit switch
88
89
90
91
92
GradeB
ook.java
default: // grade was less than 60
++fCount; // increment fCount
break; // optional; will exit switch anyway
93
94
95
} // end switch
default case for grade
} // end method incrementLetterGradeCounter
96
97
98
// display a report based on the grades entered by user
public void displayGradeReport()
99
{
100
101
102
System.out.println( "\nGrade Report:" );
103
104
if ( gradeCounter != 0 )
{
105
106
less than 60
// if user entered at least one grade...
// calculate average of all grades entered
double average = (double) total / gradeCounter;
107
Dale Roberts
(4 of 5)
Line 91 default
case
108
// output summary of results
109
System.out.printf( "Total of the %d grades entered is %d\n",
110
gradeCounter, total );
111
System.out.printf( "Class average is %.2f\n", average );
112
System.out.printf( "%s\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n",
113
"Number of students who received each grade:",
114
"A: ", aCount,
// display number of A grades
115
"B: ", bCount,
// display number of B grades
116
"C: ", cCount,
// display number of C grades
117
"D: ", dCount,
// display number of D grades
118
"F: ", fCount ); // display number of F grades
119
} // end if
120
else // no grades were entered, so output appropriate message
121
122
System.out.println( "No grades were entered" );
} // end method displayGradeReport
123 } // end class GradeBook
Dale Roberts
Outline
24
GradeB
ook.java
(5 of 5)
1
// Fig. 5.10: GradeBookTest.java
2
3
4
// Create GradeBook object, input grades and display grade report.
5
{
6
7
8
Outline
25
public class GradeBookTest
public static void main( String args[] )
{
// create GradeBook object myGradeBook and
Call GradeBook public
methods to count grades
9
10
11
// pass course name to constructor
GradeBook myGradeBook = new GradeBook(
"CS101 Introduction to Java Programming" );
12
13
14
myGradeBook.displayMessage(); // display welcome message
myGradeBook.inputGrades(); // read grades from user
15
myGradeBook.displayGradeReport(); // display report based on grades
16
} // end main
17 } // end class GradeBookTest
Dale Roberts
GradeB
ookTest
.java
(1 of 2)
Lines 13-15
Outline
Welcome to the grade book for
CS101 Introduction to Java Programming!
26
Enter the integer grades in the range 0-100.
Type the end-of-file indicator to terminate input:
On UNIX/Linux/Mac OS X type <ctrl> d then press Enter
On Windows type <ctrl> z then press Enter
99
92
45
57
63
71
76
85
90
100
^Z
Grade Report:
Total of the 10 grades entered is 778
Class average is 77.80
Number of students who received each grade:
A: 4
B: 1
C: 2
D: 1
F: 2
GradeB
ookTest
.java
(2 of 2)
Program output
Dale Roberts
Fig. 5.20 | Java’s single-entry/single-exit sequence, selection
and repetition statements.
27
Dale Roberts
Acknowledgements
Deitel, Java How to Program
Dale Roberts