dale roberts program control using java - repetition dale roberts, lecturer computer science, iupui...

28
Dale Roberts Program Control using Java Program Control using Java - Repetition - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: [email protected] Department of Computer and Information Science, School of Science, IUPUI

Upload: suzan-lane

Post on 04-Jan-2016

240 views

Category:

Documents


18 download

TRANSCRIPT

Page 1: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts

Program Control using JavaProgram Control using Java

- Repetition- Repetition

Dale Roberts, LecturerComputer Science, IUPUIE-mail: [email protected]

Department of Computer and Information Science,School of Science, IUPUI

Page 2: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts2

whilewhile Repetition Statement Repetition Statement

whilewhile statement statementRepeats an action while its loop-continuation condition Repeats an action while its loop-continuation condition remains trueremains true

Uses a merge symbol in its UML activity diagramUses a merge symbol in its UML activity diagramMerges two or more workflowsMerges two or more workflows

Represented by a diamond (like decision symbols) but has:Represented by a diamond (like decision symbols) but has:

Multiple incoming transition arrows,Multiple incoming transition arrows,

Only one outgoing transition arrow andOnly one outgoing transition arrow and

No guard conditions on any transition arrowsNo guard conditions on any transition arrows

Page 3: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts3

Fig. 4.4 Fig. 4.4 | | whilewhile repetition statement UML activity diagram. repetition statement UML activity diagram.

Page 4: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts4

Formulating Algorithms: Counter-Controlled Repetition Formulating Algorithms: Counter-Controlled Repetition

Counter-controlled repetitionCounter-controlled repetitionUse a counter variable to count the number of times a Use a counter variable to count the number of times a loop is iteratedloop is iterated

Integer divisionInteger divisionThe fractional part of an integer division calculation is The fractional part of an integer division calculation is truncated (thrown away)truncated (thrown away)

Page 5: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts5

Fig. 4.5Fig. 4.5 || Pseudocode algorithm that uses counter-controlled repetition to Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.solve the class-average problem.

11 Set total to zeroSet total to zero

22 Set grade counter to oneSet grade counter to one

33

44 While grade counter is less than or equal to tenWhile grade counter is less than or equal to ten

55 Prompt the user to enter the next gradePrompt the user to enter the next grade

66 Input the next gradeInput the next grade

77 Add the grade into the totalAdd the grade into the total

88 Add one to the grade counterAdd one to the grade counter

99

1010 Set the class average to the total divided by tenSet the class average to the total divided by ten

1111 Print the class averagePrint the class average

Page 6: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts

6OutlineOutline 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

5

6 public class GradeBook

7 {

8 private String courseName; // name of course this GradeBook represents

9

10 // constructor initializes courseName

11 public GradeBook( String name )

12 {

13 courseName = name; // initializes courseName

14 } // end constructor

15

16 // method to set the course name

17 public void setCourseName( String name )

18 {

19 courseName = name; // store the course name

20 } // end method setCourseName

21

22 // method to retrieve the course name

23 public String getCourseName()

24 {

25 return courseName;

26 } // end method getCourseName

27

•GradeBook.java (1 of 3)

Assign a value to instance variable courseName

Declare method setCourseName

Declare method getCourseName

Page 7: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts

7OutlineOutline28 // display a welcome message to the GradeBook user

29 public void displayMessage()

30 {

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

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

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

46

47 // initialization phase

48 total = 0; // initialize total

49 gradeCounter = 1; // initialize loop counter

50

•GradeBook.java (2 of 3)

Declare method displayMessage

Declare method determineClassAverage

Declare and initialize Scanner variable input

Declare local int variables total, gradeCounter, grade and average

Page 8: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts

8OutlineOutline51 // processing phase

52 while ( gradeCounter <= 10 ) // loop 10 times

53 {

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

60 // termination phase

61 average = total / 10; // integer division yields integer result

62

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

•GradeBook.java (3 of 3)

while loop iterates as long as gradeCounter <= 10

Increment the counter variable gradeCounter

Calculate average grade

Display results

Page 9: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts9

Common Programming ErrorCommon Programming Error

Using the value of a local variable Using the value of a local variable before it is initialized results in a before it is initialized results in a compilation error. All local compilation error. All local variables must be initialized before variables must be initialized before their values are used in their values are used in expressions.expressions.

Java initializes all variables to 0 by Java initializes all variables to 0 by default.default.

Page 10: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts10

Common Programming ErrorCommon Programming Error

Not providing, in the body of a Not providing, in the body of a whilewhile statement, an action that eventually statement, an action that eventually causes the condition in the causes the condition in the whilewhile to to become false normally results in a become false normally results in a logic error called an logic error called an infinite loopinfinite loop, in , in which the loop never terminates.which the loop never terminates.

Page 11: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts11

OutlineOutline

•GradeBookTest.java

1 // Fig. 4.7: GradeBookTest.java

2 // Create GradeBook object and invoke its determineClassAverage method.

3

4 public class GradeBookTest

5 {

6 public static void main( String args[] )

7 {

8 // create GradeBook object myGradeBook and

9 // pass course name to constructor

10 GradeBook myGradeBook = new GradeBook(

11 "CS101 Introduction to Java Programming" );

12

13 myGradeBook.displayMessage(); // display welcome message

14 myGradeBook.determineClassAverage(); // find average of 10 grades

15 } // end main

16

17 } // end class GradeBookTest

Welcome to the grade book for CS101 Introduction to Java Programming! Enter grade: 67 Enter grade: 78 Enter grade: 89 Enter grade: 67 Enter grade: 87 Enter grade: 98 Enter grade: 93 Enter grade: 85 Enter grade: 82 Enter grade: 100 Total of all 10 grades is 846 Class average is 84

Create a new GradeBook object

Pass the course’s name to the GradeBook constructor as a string

Call GradeBook’s determineClassAverage method

Page 12: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts12

Formulating Algorithms: Sentinel-Controlled Repetition Formulating Algorithms: Sentinel-Controlled Repetition

Sentinel-controlled repetitionSentinel-controlled repetitionAlso known as indefinite repetitionAlso known as indefinite repetition

Use a sentinel value (also known as a signal, dummy or Use a sentinel value (also known as a signal, dummy or flag value)flag value)

A sentinel value cannot also be a valid input valueA sentinel value cannot also be a valid input value

Page 13: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts13

Common Programming Error 4.6Common Programming Error 4.6

Choosing a sentinel value that is also Choosing a sentinel value that is also a legitimate data value is a logic error.a legitimate data value is a logic error.

Page 14: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts14

Fig. 5.3 Fig. 5.3 | | forfor statement header components. statement header components.

Page 15: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts15

UML activity diagram for the UML activity diagram for the forfor statement in Fig. 5.2. statement in Fig. 5.2.

Page 16: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts16

5.3 5.3 forfor Repetition Statement (Cont.) Repetition Statement (Cont.)forfor ( ( initializationinitialization; ; loopContinuationConditionloopContinuationCondition; ; increment increment ) )

statementstatement;;

can usually be rewritten as:can usually be rewritten as:

initializationinitialization;;whilewhile ( ( loopContinuationCondition loopContinuationCondition ) )

{{ statementstatement;; incrementincrement;;}}

Page 17: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts17

5.4 Examples Using the 5.4 Examples Using the forfor Statement Statement

Varying control variable in Varying control variable in forfor statement statementVary control variable from Vary control variable from 11 to to 100100 in increments of in increments of 11

forfor ( ( intint i = i = 11; i <= ; i <= 100100; i++ ); i++ )Vary control variable from Vary control variable from 100100 to to 11 in increments of in increments of –1–1

forfor ( ( intint i = i = 100100; i >= ; i >= 11; i-- ); i-- )Vary control variable from Vary control variable from 77 to to 7777 in increments of in increments of 77

forfor ( ( intint i = i = 77; i <= ; i <= 7777; i += ; i += 77 ) )Vary control variable from Vary control variable from 2020 to to 22 in decrements of in decrements of 22

forfor ( ( intint i = i = 2020; i >= ; i >= 22; i -= ; i -= 22 ) )Vary control variable over the sequence: Vary control variable over the sequence: 22, , 55, , 88, , 1111, , 1414, , 1717, , 2020

forfor ( ( intint i = i = 22; i <= ; i <= 2020; i += ; i += 33 ) )Vary control variable over the sequence: Vary control variable over the sequence: 9999, , 8888, , 7777, , 6666, , 5555, , 4444, , 3333, , 2222, , 1111, , 00

forfor ( ( intint i = i = 9999; i >= ; i >= 00; i -= ; i -= 1111 ) )

Page 18: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts

18OutlineOutline

DoWhileTest.jDoWhileTest.javaava

Line 8Line 8

Lines 10-14Lines 10-14

Program Program outputoutput

1 // Fig. 5.7: DoWhileTest.java

2 // do...while repetition statement.

3

4 public class DoWhileTest

5 {

6 public static void main( String args[] )

7 {

8 int counter = 1; // initialize counter

9

10 do

11 {

12 System.out.printf( "%d ", counter );

13 ++counter;

14 } while ( counter <= 10 ); // end do...while

15

16 System.out.println(); // outputs a newline

17 } // end main

18 } // end class DoWhileTest 1 2 3 4 5 6 7 8 9 10

Declares and initializes control variable counter

Variable counter’s value is displayed before testing counter’s final value

Page 19: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts19

Fig. 5.8 Fig. 5.8 | | do...whiledo...while repetition statement UML activity repetition statement UML activity diagram. diagram.

Page 20: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts

20OutlineOutline

GradeBookGradeBook.java.java(1 of 5)(1 of 5)

Lines 8-14Lines 8-14

1 // Fig. 5.9: GradeBook.java 2 // GradeBook class uses switch statement to count A, B, C, D and F grades. 3 import java.util.Scanner; // program uses class Scanner 4 5 public class GradeBook 6 { 7 private String courseName; // name of course this GradeBook represents 8 private int total; // sum of grades 9 private int gradeCounter; // number of grades entered 10 private int aCount; // count of A grades 11 private int bCount; // count of B grades 12 private int cCount; // count of C grades 13 private int dCount; // count of D grades 14 private int fCount; // count of F grades 15 16 // constructor initializes courseName; 17 // int instance variables are initialized to 0 by default 18 public GradeBook( String name ) 19 { 20 courseName = name; // initializes courseName 21 } // end constructor 22 23 // method to set the course name 24 public void setCourseName( String name ) 25 { 26 courseName = name; // store the course name 27 } // end method setCourseName 28

Page 21: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts

21OutlineOutline

GradeBoGradeBook.javaok.java(2 of 5)(2 of 5)

Lines 50-54Lines 50-54

29 // method to retrieve the course name

30 public String getCourseName()

31 {

32 return courseName;

33 } // end method getCourseName

34

35 // display a welcome message to the GradeBook user

36 public void displayMessage()

37 {

38 // getCourseName gets the name of the course

39 System.out.printf( "Welcome to the grade book for\n%s!\n\n",

40 getCourseName() );

41 } // end method displayMessage

42

43 // input arbitrary number of grades from user

44 public void inputGrades()

45 {

46 Scanner input = new Scanner( System.in );

47

48 int grade; // grade entered by user

49

50 System.out.printf( "%s\n%s\n %s\n %s\n",

51 "Enter the integer grades in the range 0-100.",

52 "Type the end-of-file indicator to terminate input:",

53 "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",

54 "On Windows type <ctrl> z then press Enter" );

55

Display prompt

Page 22: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts

22OutlineOutline

GradeBoGradeBook.javaok.java(3 of 5)(3 of 5)

Line 57Line 57

Line 72 controlling Line 72 controlling expressionexpression

Lines 72-94Lines 72-94

56 // loop until user enters the end-of-file indicator 57 while ( input.hasNext() ) 58 { 59 grade = input.nextInt(); // read grade 60 total += grade; // add grade to total 61 ++gradeCounter; // increment number of grades 62 63 // call method to increment appropriate counter 64 incrementLetterGradeCounter( grade ); 65 } // end while 66 } // end method inputGrades 67 68 // add 1 to appropriate counter for specified grade 69 public void incrementLetterGradeCounter( int numericGrade ) 70 { 71 // determine which grade was entered 72 switch ( grade / 10 ) 73 { 74 case 9: // grade was between 90 75 case 10: // and 100 76 ++aCount; // increment aCount 77 break; // necessary to exit switch 78 79 case 8: // grade was between 80 and 89 80 ++bCount; // increment bCount 81 break; // exit switch 82

Loop condition uses method hasNext to determine whether there is more data to input

switch statement determines which case label to execute, depending on

controlling expression

(grade / 10 ) is controlling expression

Page 23: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts

23OutlineOutline

GradeBoGradeBook.javaok.java(4 of 5)(4 of 5)

Line 91 default caseLine 91 default case

83 case 7: // grade was between 70 and 79

84 ++cCount; // increment cCount

85 break; // exit switch

86

87 case 6: // grade was between 60 and 69

88 ++dCount; // increment dCount

89 break; // exit switch

90

91 default: // grade was less than 60

92 ++fCount; // increment fCount

93 break; // optional; will exit switch anyway

94 } // end switch

95 } // end method incrementLetterGradeCounter

96

97 // display a report based on the grades entered by user

98 public void displayGradeReport()

99 {

100 System.out.println( "\nGrade Report:" );

101

102 // if user entered at least one grade...

103 if ( gradeCounter != 0 )

104 {

105 // calculate average of all grades entered

106 double average = (double) total / gradeCounter;

107

default case for grade less than 60

Page 24: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts

24OutlineOutline

GradeBook.javGradeBook.javaa(5 of 5)(5 of 5)

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 System.out.println( "No grades were entered" );

122 } // end method displayGradeReport

123 } // end class GradeBook

Page 25: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts

25OutlineOutline

GradeBooGradeBookTest.javakTest.java(1 of 2)(1 of 2)

Lines 13-15Lines 13-15

1 // Fig. 5.10: GradeBookTest.java

2 // Create GradeBook object, input grades and display grade report.

3

4 public class GradeBookTest

5 {

6 public static void main( String args[] )

7 {

8 // create GradeBook object myGradeBook and

9 // pass course name to constructor

10 GradeBook myGradeBook = new GradeBook(

11 "CS101 Introduction to Java Programming" );

12

13 myGradeBook.displayMessage(); // display welcome message

14 myGradeBook.inputGrades(); // read grades from user

15 myGradeBook.displayGradeReport(); // display report based on grades

16 } // end main

17 } // end class GradeBookTest

Call GradeBook public methods to count grades

Page 26: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts

26OutlineOutline

GradeBooGradeBookTest.javakTest.java(2 of 2)(2 of 2)

Program outputProgram output

Welcome to the grade book for CS101 Introduction to Java Programming! 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

Page 27: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts27

Fig. 5.20 Fig. 5.20 | | Java’s single-entry/single-exit sequence, selection Java’s single-entry/single-exit sequence, selection and repetition statements. and repetition statements.

Page 28: Dale Roberts Program Control using Java - Repetition Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu Department of Computer

Dale Roberts

AcknowledgementsAcknowledgementsDeitel, Java How to Program