Transcript Ch7

Repetition of Statements
• Repetition of statements is a further
common facet of everyday life and object
behavior:
– Repeat every day: Get up; have breakfast; go
off to work; have lunch; do more work; have an
evening meal; relax; go to bed.
• Java has three types of loop for repetition:
– while, do, for.
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
1
The While Loop
•Controlled by a Boolean expression.
•Beware of its (syntactic) similarity to the
simple if statement.
while(condition){
// Repeat multiple statements.
statement;
statement;
statement;
...
}
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
2
Adding Salt to Soup
public void saltTheSoup(){
while(there isn't enough salt in the soup){
Add a pinch of salt;
}
}
•Note that the number of pinches added is
arbitrary and variable.
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
3
Printing a Sequence
// Print the numbers 1 to maximum.
public void printNumbers(int maximum){
int nextToPrint = 1;
while(nextToPrint <= maximum){
System.out.print(nextToPrint+" ");
// Get ready to print the next number.
nextToPrint += 1;
}
System.out.println();
}
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
4
Reading Input Values
SimpleInput keyboard = new SimpleInput();
BarChartMinder minder = new BarChartMinder(
new BarChart());
int terminatingValue = -1;
System.out.println("Please input the values, use "+
terminatingValue+" to finish.");
int value = keyboard.nextInt();
while(value != terminatingValue){
minder.addToChart(value);
value = keyboard.nextInt();
}
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
5
The Do Loop
do{
// Repeat multiple statements.
statement;
statement;
statement;
...
} while(condition);
•Note that the statements in the body of the
loop are always executed at least one.
•Note the final semicolon, which is required.
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
6
Printing a Sequence
public void printNumbers(int maximum){
int nextToPrint = 1;
do{
System.out.print(nextToPrint+" ");
// Get ready to print the next number.
nextToPrint += 1;
}
while(nextToPrint <= maximum);
System.out.println();
}
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
7
The For Loop
• Used to repeat statements a fixed number of
times:
– Add three teaspoons of sugar.
– Knock twice and then give the password.
• Used very often with arrays and collections
of objects - see later chapters.
• Similar in effect to the while loop.
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
8
The For-Loop Outline
// Repeat multiple statements.
for(initialization; condition; post-body update){
// Statements to be repeated.
statement;
statement;
statement;
...
}
•Commonly used with increment and decrement
operators.
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
9
Increment and Decrement
• Used as a shorthand for add-one-to and
subtract-one-from:
• value = value+1;
• value += 1;
• value++;
• Prefix and postfix forms:
• ++value;
• --value;
• value--;
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
10
A For Loop to Print a Sequence
public void printNumbers(int maximum){
for(int nextToPrint = 1; nextToPrint <= maximum;
nextToPrint++){
System.out.print(nextToPrint+" ");
}
System.out.println();
}
•Note the loop variable declaration in situ.
•The variable is not available outside the loop.
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
11
Optional Header Expressions
• All expressions in a for loop's header are
optional.
• Omission of the middle expression (the
condition) creates a potentially infinite loop.
• The two outer expressions do not have to be
explicitly concerned with loop control.
– They usually are, however.
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
12
For Loop Variations
// Countdown.
for( ; n >= 0; n--){
System.out.println(n);
}
// Print forever.
for(int n = 0; ; n++){
System.out.println(n);
}
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
13
The Comma Operator
// Use isPrime to count the number of prime
// numbers from 2 to max.
public int countPrimes(int max){
int numPrimes, possible;
for(numPrimes = 0, possible = 2;
possible <= max;
possible++){
if(isPrime(possible)){
numPrimes++;
}
}
return numPrimes;
}
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
14
Code Blocks and Scope
• The bodies of control structures define a
further scope level:
– Class body.
– Method body.
– Control structure body.
• Variables may be defined within each.
– Scope of a variable is limited to its defining
block.
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
15
Localized Definition and Use
int x, y;
// Statements using x and y.
...
if(x > y){
// Swap the values held in x and y.
// Hold onto the value of x.
int temp = x;
// Copy y's value into x.
x = y;
// Copy into y the old value of x.
y = temp;
}
...
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
16
Final Variables and Arguments
• The final modifier may be used to
indicate a constant value.
– final int DOZEN = 12;
– final double NUMDEGREES = 360.0;
• Uppercase names commonly used for
special values.
• Normal naming used simply for
optimization.
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
17
Final Fields and Constructors
• A final field must be initialized:
– In its declaration, or
– Within all of its class's constructors.
– Within an initializer block.
• Like a method without a body.
• An uninitialized final field is a blank final
variable.
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
18
Static Variables
• Only available as fields of a class.
– Method variables cannot be static.
• Commonly used to provide global access to
constant values of significance:
– public static final int Jan = 1, ...
• Static variables exist independently of
instances.
– Instances share the same static variables.
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
19
Static Methods
• Also known as class methods.
• Static methods are invoked through the
name of their containing class:
– double rand = Math.random();
• A static method may not access non static
members of its containing class.
– Static methods exist independently of instances.
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
20
Review
• Java's three loops provide for different
styles of repetition.
• For loops often used for bounded repetition.
• Conditional and loop statement bodies
introduce a further level of scope.
– Variables may be defined within them.
• Static variables and methods exist
independently from any instance.
OOP with Java, David
J. Barnes
Adding Repetitive Behavior
21