Download Java_4A Control Structures: Part 1

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
1
Java_4A Control Structures: Part 1
Outline
4.1
4.2
4.3
4.4
4.5
4.6
4.7
4.8
Algorithms
Control Structures
if Single-Selection Statement
if else Selection Statement
while Repetition Statement
Formulating Algorithms: Counter-Controlled Repetition
Formulating Algorithms: Sentinel-Controlled Repetition
Formulating Algorithms: Nested Control Statements
2
4.1
Algorithms
• Algorithm
– Series of actions in specific order
• The actions executed
• The order in which actions execute
• Program control
– Specifying the order in which actions execute
• Control structures help specify this order
3
4.2
Control Structures
• Sequential execution
– Program statements execute one after the other
• Transfer of control
– Three control statements can specify order of statements
• Sequence structure
• Selection structure
• Repetition structure
• Activity diagram
– Models the workflow
• Action-state symbols
• Transition arrows
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.
5
4.2
Control Structures
• Java has a sequence structure “built-in”
• 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
6
4.3
if Single-Selection Statement
• Single-entry/single-exit control structure
• Perform action only when condition is true
• Action/decision programming model
7
[grade >= 60]
print “Passed”
[grade < 60]
Fig 4.3 if single-selections statement activity diagram.
8
4.4
if…else Selection Statement
• Perform action only when condition is true
• Perform different specified action when condition
is false
• Conditional operator (?:)
• Nested if…else selection structures
9
[grade < 60]
print “Failed”
[grade >= 60]
print “Passed”
Fig 4.4 if…else double-selections statement activity diagram.
10
4.5
while Repetition Statement
• Repeat action while condition remains true
11
merge
decision
[product <= 1000]
double product value
[product > 1000]
Corresponding Java statement:
product = 2 * product;
Fig 4.5 while repetition statement activity diagram.
12
4.6
Formulating Algorithms: CounterControlled Repetition
• Counter
– Variable that controls number of times set of statements
executes
• Average1.java calculates grade averages
– uses counters to control repetition
13
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
// ClassClass-average program with countercounter-controlled repetition.
import javax.swing.JOptionPane;
javax.swing.JOptionPane;
Declare variables;
gradeCounter is the counter
public class Average1 {
public
{
int
int
int
int
static void main( String args[]
args[] )
total;
gradeCounter;
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;
gradeString; // grade typed by
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(
JOptionPane.showInputDialog(
"Enter integer grade: " );
// convert gradeString to int
grade = Integer.parseInt(
Integer.parseInt( gradeString );
Outline
Average1.java
gradeCounter
Line 21
14
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
Average1.java
// termination phase
average = total / 10;
10;
// integer division
// display average of exam grades
JOptionPane.showMessageDialog(
JOptionPane.showMessageDialog( null,
null, "Class average is " + average,
"Class Average",
Average", JOptionPane.INFORMATION_MESSAGE );
System.exit( 0 );
} // end main
} // end class Average1
Outline
// terminate the program
15
Outline
Average1.java
16
Using while statement with classes
• Problem statement:
• A class of ten students took a quiz. The grades
(integers in the range 0 to 100) for this quiz are
available to you. Determine the class average on
the quiz.
17
// GradeBook class that solves classclass-average problem using
// countercounter-controlled repetition.
repetition.
import java.
java.util.Scanner;
util.Scanner; // program uses class Scanner
public class GradeBook
{
private String courseName;
courseName; // name of course this GradeBook represents
// constructor initializes courseName
public GradeBook(
GradeBook( String name )
{
courseName = name;
name; // initializes courseName
} // end constructor
// method to set the course name
public void setCourseName(
setCourseName( String name )
{
courseName = name;
name; // store the course name
} // end method setCourseName
// method to retrieve the course name
public String getCourseName()
getCourseName()
{
return courseName;
courseName;
} // end method getCourseName
Outline
18
// display a welcome message to the GradeBook user
public void displayMessage()
displayMessage()
{
// getCourseName gets the name of the course
System.out.printf(
System.out.printf( "Welcome to the grade book for\
for\n%s!\
n%s!\n\n",
getCourseName()
getCourseName() );
} // end method displayMessage
// determine class average based on 10 grades entered by user
public void determineClassAverage()
determineClassAverage()
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );
int
int
int
int
total; // sum of grades entered by user
gradeCounter;
gradeCounter; // number of the grade to be entered next
grade; // grade value entered by user
average; // average of grades
// initialization phase
total = 0; // initialize total
gradeCounter = 1; // initialize loop counter
Outline
19
// processing phase
while ( gradeCounter <= 10 ) // loop 10 times
{
System.
System.out.
out.print(
print( "Enter
"Enter grade: " ); // prompt
grade = input.
input.nextInt();
nextInt(); // read grade from user
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter by 1
} // end while
// termination phase
average = total / 10; // integer division yields integer result
// display total and average of grades
System.
System.out.
out.printf(
printf( "\
"\nTotal of all 10 grades is %d\
%d\n", total );
System.
System.out.
out.printf(
printf( "Class
"Class average is %d\
%d\n", average );
} // end method determineClassAverage
} // end class GradeBook
Outline
20
// Create GradeBook object and invoke its classAverage method.
method.
public class GradeBookTest
{
public static void main(
main( String args[]
args[] )
{
// create GradeBook object myGradeBook and
// pass course name to constructor
GradeBook myGradeBook = new GradeBook(
GradeBook(
"CS101 Introduction to Java Programming"
Programming" );
myGradeBook.
myGradeBook.displayMessage();
displayMessage(); // display welcome message
myGradeBook.
myGradeBook.determineClassAverage();
determineClassAverage(); // find average of 10 grades
} // end main
} // end class GradeBookTest
Outline
21
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:
10
5
9
12
19
24
24
10
12
34
Total of all 10 grades is 156
Class average is 15,6
Outline
22
4.7
Formulating Algorithms: SentinelControlled Repetition
• Sentinel value
– Used to indicated the end of data entry
• indefinite repetition
– User enters sentinel value (-1) to end repetition
• Develop a class-average program that processes
grades for an arbitrary number of students each
time it is run.
23
// GradeBook class that solves classclass-average program using
// sentinelsentinel-controlled repetition.
repetition.
import java.
java.util.Scanner;
util.Scanner; // program uses class Scanner
public class GradeBook
{
private String courseName;
courseName; // name of course this GradeBook represents
// constructor initializes courseName
public GradeBook(
GradeBook( String name )
{
courseName = name;
name; // initializes courseName
} // end constructor
// method to set the course name
public void setCourseName(
setCourseName( String name )
{
courseName = name;
name; // store the course name
} // end method setCourseName
// method to retrieve the course name
public String getCourseName()
getCourseName()
{
return courseName;
courseName;
} // end method getCourseName
Outline
24
// display a welcome message to the GradeBook user
public void displayMessage()
displayMessage()
{
// getCourseName gets the name of the course
System.
System.out.
out.printf(
printf( "Welcome
"Welcome to the grade book for\
for\n%s!\
n%s!\n\n",
getCourseName()
getCourseName() );
} // end method displayMessage
// determine the average of an arbitrary number of grades
public void determineClassAverage()
determineClassAverage()
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in
System.in );
int total;
total; // sum of grades
int gradeCounter;
gradeCounter; // number of grades entered
int grade; // grade value
double average;
average; // number with decimal point for average
// initialization phase
total = 0; // initialize total
gradeCounter = 0; // initialize loop counter
// processing phase
// prompt for input and read grade from user
System.
System.out.
out.print(
print( "Enter
"Enter grade or -1 to quit:
quit: " );
grade = input.
input.nextInt();
nextInt();
Outline
25
// loop until sentinel value read from user
while ( grade != -1 )
{
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter
// prompt for input and read next grade from user
System.
System.out.
out.print(
print( "Enter
"Enter grade or -1 to quit:
quit: " );
grade = input.
input.nextInt();
nextInt();
} // end while
// termination phase
// if user entered at least one grade...
if ( gradeCounter != 0 )
{
// calculate average of all grades entered
average = (double) total / gradeCounter;
gradeCounter;
// display total and average (with two digits of precision)
precision)
System.
System.out.
out.printf(
printf( "\
"\nTotal of the %d grades entered is %d\
%d\n",
gradeCounter,
gradeCounter, total );
System.
System.out.
out.printf(
printf( "Class
"Class average is %.2f\
%.2f\n", average );
} // end if
else // no grades were entered,
entered, so output appropriate message
System.
System.out.
out.println(
println( "No grades were entered"
entered" );
} // end method determineClassAverage
} // end class GradeBook
Outline
26
// Create GradeBook object and invoke its determineClassAverage method.
method.
public class GradeBookTest
{
public static void main(
main( String args[]
args[] )
{
// create GradeBook object myGradeBook and
// pass course name to constructor
GradeBook myGradeBook = new GradeBook(
GradeBook(
"CS101 Introduction to Java Programming"
Programming" );
myGradeBook.
myGradeBook.displayMessage();
displayMessage(); // display welcome message
myGradeBook.
myGradeBook.determineClassAverage();
determineClassAverage(); // find average of grades
} // end main
} // end class GradeBookTest
Outline
27
Welcome to the grade book for
CS101 Introduction to Java Programming!
Enter
Enter
Enter
Enter
Enter
Enter
Enter
Enter
grade
grade
grade
grade
grade
grade
grade
grade
or
or
or
or
or
or
or
or
-1
-1
-1
-1
-1
-1
-1
-1
to
to
to
to
to
to
to
to
quit:
quit:
quit:
quit:
quit:
quit:
quit:
quit:
12
84
52
128
650
210
42
-1
Total of the 7 grades entered is 1178
Class average is 168,2857
Outline
28
4.8
•
•
Formulating Algorithms: Nested
Control Structures
Problem statement:
Program should analyze the results of the exam
as follows:
1. Input each test result (i.e. a 1 or a 2). Display message
“Enter result” on the screen aech time the program requires
another test result.
2. Count the number of test results of each type.
3. Display a summary of the test results including the number
of students who passed and number od f students who
failed
4. If more that eight students passed the exam, print the
message “Raise tuition”
29
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
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.
30
// Analysis of examination results.
results.
import java.
java.util.Scanner;
util.Scanner; // class uses class Scanner
public class Analysis
{
public void processExamResults()
processExamResults()
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in
System.in );
// initializing variables in declarations
int passes = 0; // number of passes
int failures = 0; // number of failures
int studentCounter = 1; // student counter
int result;
result; // one exam result (obtains value from user)
user)
// process 10 students using countercounter-controlled loop
while ( studentCounter <= 10 )
{
// prompt user for input and obtain value from user
System.
System.out.
out.print(
print( "Enter
"Enter result (1 = pass,
pass, 2 = fail):
fail): " );
result = input.
input.nextInt();
nextInt();
// if
if...
...else
...else nested in while
if ( result == 1 )
//
passes = passes + 1;
//
else
//
failures = failures + 1; //
if result 1,
increment passes;
passes;
else result is not 1, so
increment failures
Outline
31
// increment studentCounter so loop eventually terminates
studentCounter = studentCounter + 1;
} // end while
// termination phase;
phase; prepare and display results
System.
System.out.
out.printf(
printf( "Passed
"Passed:
Passed: %d\
%d\nFailed:
nFailed: %d\
%d\n", passes,
passes, failures );
// determine whether more than 8 students passed
if ( passes > 8 )
System.
System.out.
out.println(
println( "Raise Tuition"
Tuition" );
} // end method processExamResults
} // end class Analysis
Outline
32
// Test program for class Analysis.
Analysis.
public class AnalysisTest
{
public static void main(
main( String args[]
args[] )
{
Analysis application = new Analysis();
Analysis(); // create Analysis object
application.
application.processExamResults();
processExamResults(); // call method to process results
} // end main
} // end class AnalysisTest
Outline
33
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Enter result (1
Passed: 9
Failed: 1
Raise Tuition
=
=
=
=
=
=
=
=
=
=
pass,
pass,
pass,
pass,
pass,
pass,
pass,
pass,
pass,
pass,
2
2
2
2
2
2
2
2
2
2
=
=
=
=
=
=
=
=
=
=
fail):
fail):
fail):
fail):
fail):
fail):
fail):
fail):
fail):
fail):
1
2
1
1
1
1
1
1
1
1
Outline