why do we use iteration 10. iteration 1courses.cs.vt.edu/~cs1054/notes/10.iteration.pdfwhy do we use...
TRANSCRIPT
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
110. Iteration
Programming in Java
Why do we use iteration
! So far we’ve done projects with a very limited number of objects! What if an unknown number of data records?! What if you had an account management system that had to deal with 1000
transactions?
Couldn’t rely on fixed code segmentto process specific number of moves.
It would be silly to copy and paste code toprocess a transaction 1000 times.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
210. Iteration
Programming in Java
Iteration Terms
! Definitions:Before considering specifics we define some general terms that apply to any iteration construct:
pass (or iteration) - one complete execution of the bodyloop entry - the point where flow of control passes to the bodyloop test - the point at which the decision is made to (re)enter
the body, or notloop exit - the point at which the iteration ends and control
passes to the next statement after the looptermination condition - the condition that causes the iteration to stop
When designing a loop, it is important to clearly identify each of these.
Understanding the termination condition, and what guarantees it will eventually occur, are particularly vital.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
310. Iteration
Programming in Java
The While Statement
Syntax: while ( condition )body
1. Test condition2. if condition evaluates to false, terminate loop and
continue with statement after body3. if condition is true, execute body statement and
start over
IMPORTANT: The body must have the “power” to change the outcome of the condition!!!
Semantics:
while <bool expr>
<loop body>
true
false
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
410. Iteration
Programming in Java
The While Statement - variations
while ( someCondition )doSomething;
while (someOtherCondition) {doSomethingA;someObject.doSomethingB();doSomethingC;
}
while (someCondition);doSomethingElse;
Fine!
Fine!(notice thebrackets)
Problem!!Why?
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
510. Iteration
Programming in Java
Example problem:
! An input file stores employee work data. – In the file, one line will contain employee information, and the next will contain
the number of hours the employee worked. – There are an unknown number of employees.
! We can use the static method Employee.readIn(bufRdr)…to get employee data, and the non-static method
public String calcPay(int hours)
…to compute and return that employee’s pay.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
610. Iteration
Programming in Java
Example – what’s wrong here?
int hours = 0;Employee e;
while ( e != null ) {e = Employee.readIn(br);
hours = Integer.parseInt(br.readLine());System.out.println(”Employee ” + e.getName() +
”has earned ” + e.calcPay(hours));}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
710. Iteration
Programming in Java
Example – what’s wrong here?
int hours = 0;Employee e = Employee.readIn(br); // OK! Fixed!
while ( e != null ) {hours = Integer.parseInt(br.readLine());System.out.println(”Employee ” + e.getName() +
”has earned ” + e.calcPay(hours));}
Infinite loop!“e” never changes!
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
810. Iteration
Programming in Java
Example – this will work!
int hours = 0;Employee e = Employee.readIn(br);
while ( e != null ) {hours = Integer.parseInt(br.readLine());System.out.println(”Employee ” + e.getName() +
”has earned ” + e.calcPay(hours));e = Employee.readIn(br);
}
Called a“priming read”
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
910. Iteration
Programming in Java
Input Loop Pattern
int hours = 0;Employee e = Employee.readIn(br);while ( e != null ) {
hours = Integer.parseInt(br.readLine());System.out.println(”Employee ” + e.getName() +
”has earned ” + e.calcPay(hours));e = Employee.readIn(br);
}
First read input
Test input OK
Read input for next iteration
How does this loop terminate?
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1010. Iteration
Programming in Java
Another Example
int i;String tmp;tmp = br.readLine();while ( tmp != null ) {
i = Integer.parseInt(tmp);System.out.print ( i * i );temp = br.readLine();
}
What does this code do, exactly ?
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1110. Iteration
Programming in Java
Input Loop Pattern
read first itemwhile ( input is OK or item valid ) {
process itemread next item
}
Some observations:
- It is possible that the body of the loop will never be executed.
- It is possible that the loop test condition will become false in the middle of an iteration. Even so, the remainder of the loop body will be executed before the loop test is performed and iteration stops.
- The loop test must involve at least one variable whose value is (potentially) changed by at least one statement within the loop body.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1210. Iteration
Programming in Java
Example:
! Song library – files in the format:TitleArtistTitleArtist(etc…)
LaylaEric ClaptonRevolutionBeatlesYesterdayBeatlesHouse of the Rising SunThe AnimalsLike a Rolling StoneDylan, Bob(...)
File: “classicRock.lib”
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1310. Iteration
Programming in Java
Example:
! The DJ wants to be able to query a song database by typing an artist and getting all matching songs.
! First bit of code:
public static Song read(BufferedReader br)
throws Exception {
String title = br.readLine();
if (title == null)
return null;
String artist = br.readLine();
return new Song(title, artist);
}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1410. Iteration
Programming in Java
Example:
! For each query, we’ll need to open the database and read all the way through.
! Possible use of our “SongLibrary” class:
SongLibrary rock = new SongLibrary(“classicRock.lib”);
String artist = myInterIO.promptAndRead(“Artist? ”)
while (artist!=“STOP”){
rock.lookUp(artist);
artist = myInterIO.promptAndRead(“Artist? ”)
}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1510. Iteration
Programming in Java
Example:
public void lookup(String artist)
throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(songFileName)));
Song song = Song.read(br);
while (song != null){
if (artist.equals(song.getArtist() ) )
System.out.println(song.getTitle() );
song = Song.read(br);
}
}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1610. Iteration
Programming in Java
Loop Design Considerations
! Questions that one should consider carefully when coding a loop:
- What is the condition that terminates the loop?
- How should the condition be initialized?
- How should the condition be updated?
- What guarantees this condition will eventually occur?
- What is the process to be repeated?
- How should the process be initialized?
- How should the process be updated?
- What is the state of the program on exiting the loop?
- Are "boundary conditions" handled correctly?
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1710. Iteration
Programming in Java
Maintaining multiple values
! The SongLibrary example allowed us to read and process an indeterminate number of records, but…
! We could only have one record, (object), in memory at any one time.! What if we wanted to read a list and then:
– reverse it– sort it– build a concordance
We’d have to have the whole list in memory at once!
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1810. Iteration
Programming in Java
The Vector class
! Just like a mathematical vector stores an ordered collection of numeric values, a Java Vector object stores an ordered collection of objects.String s;
Vector v = new Vector();
s = br.readLine();
while (s != null) {
v.addElement(s);
s.br.readLine();
}
System.out.print(V.size());
This allows us to Read and store an indeterminate number of strings (or any type of object), but how do we then read or process them?
The Vector addElement() method is used for storing elements in the vector.The Vector size() method returns the number of elements in the vector.The Vector isEmpty() method returns false if any elements are in the vector.Many other vector methods exist in the Vector class for use.
The Vector class is a container class.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
1910. Iteration
Programming in Java
The Enumeration class
! The Vector class has a method, elements() , that returns an Enumeration object.
! The Enumeration class has the methods:boolean hasMoreElements();
someType nextElement();
The enumeration class models the behavior of traversing the elements of the collection, in this case the vector. Other Java container/collection classes also use the enumeration class to provide traversal services for visiting and processing each element of the collection.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2010. Iteration
Programming in Java
The Enumeration class
Enumeration myEnum = v.elements();
while (myEnum.hasMoreElements()){
String s = (String) myEnum.nextElement();
System.out.print(s);
}
This is an example of the traversal pattern using an enumeration to visit and process each element stored in the collection in sequence.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2110. Iteration
Programming in Java
The Enumeration class
Type cast!
Enumeration myEnum = v.elements();
while (myEnum.hasMoreElements() ){
String s = (String) myEnum.nextElement();
System.out.print(s);
}
The typecast is required to assign the reference returned by nextElement() to a specific reference variable since by default nextElement() returns a generic object type reference.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2210. Iteration
Programming in Java
The SongLibrary class, again
! Using the Vector and Enumeration classes, we could modify our SongLibraryclass so that we only have to read the database file once! Then we can query our vector object as many times as we want!
! See text, pages 284-285 for example.
! Exercise: plan out a means by which you could read in & query the song database, make additions, and then re-save to an updated file!
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2310. Iteration
Programming in Java
Example: a “Set” class
! Problem: Create a container class to implement the mathematical concept of a Set.
! We need the following behavior (methods):– Set (constructor)– contains (test for membership in the set)– isEmpty (see if this is the “null set”)– addElement (as name implies)– copy (to make a copy of the set)– size (number of elements in the set)– elements (returns an enumeration)– union (returns a set containing only elements in both)– intersection (returns a set containing all elements of each)– print (as name implies)
Since the Set class will also be a container class consistency should be maintained with the other container classes, (e.g., the Vector class). Thus the method names: addElement(), size(), & elements() were selected.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2410. Iteration
Programming in Java
Example: a “Set” class
! … so we’ll only need the followinginstance variable in the Set class:
Vector v;
– Note: the book uses this example, and makes several errors, because sometimes it calls this instance variable “theElements” and sometimes it calls it “vector”. We’ll just call it “v”.
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2510. Iteration
Programming in Java
Set class – “size” method
public int size(){
return v.size();
}
A very simple method!
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2610. Iteration
Programming in Java
Set class – “elements” method
public Enumeration elements(){
return v.elements();
}
Another simple one!
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2710. Iteration
Programming in Java
Set class – “addElement” method
Public member method of the Set class.
public void addElement(Object s){
if ( ! contains(s) )
v.addElement(s);
}
The behavior of the: addElement(), method is one aspect of the the Set class that is different from the vector class. The other behaviors that distinguish Sets from vectors is the union and intersection methods. .
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2810. Iteration
Programming in Java
Set class – “intersection” method
public Set intersection(Set other){
Set interSet = new Set();
Enumeration enum = this.v.elements();
while ( enum.hasMoreElemets() ){
Object elem = enum.nextElement();
if ( other.contains(elem) )
interSet.addElement(elem);
}
return interSet;
}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
2910. Iteration
Programming in Java
Set class – “union” method
Public member method of the Set class.
public Set union(Set other){
Set unionSet = other.copy();
Enumeration enum = this.v.elements();
while ( enum.hasMoreElemets() ){
unionSet.addElement(enum.nextElement());
}
return unionSet ;
}
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
3010. Iteration
Programming in Java
Set class – “copy” method
public Set copy (){
Set target = new Set();
Enumeration source = v.elements();
while (source.hasMoreElements())
target.addElement( source.nextElement() );
return target;
}
Why is the copy method necessary for the Set class. Why not allow the user to simply code:
Set A, B;//… add elements to Set AB = A;
Computer Science Dept Va Tech August 2002 ©2002 D Barnette, B Keller & P Schoenhoff
3110. Iteration
Programming in Java
Set class – “contains” method
public boolean contains(Object o){
Enumeration enum = v.elements();
while ( enum.hasMoreElements() ){
Object item = enum.nextElement();
if (item.equals(o)) return true;
}
return false;
}
Note: the object class represents all object types. The object class contains a general equals method for comparing any two objects. In reality the general equals method does not compare any two objects. It relies upon the specific classes providing their own equals method which is automagically used. The Java predefined classes, (String, Integer), provides their own equalsmethods. To store user defined objects in the Set class we must provide an appropriate and specific equals method in our classes.