RU beehive logo ITEC dept promo banner
ITEC 120
2008spring
ibarland,
jdymacek

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lect12c
while loops, continued
closing thoughts

lists and while

Processing a list using while and get() For example:
Suppose doggies is a list of Dog.

// A for-each loop to add all the ages of every Dog in doggies.
int agesSoFar = 0;
for ( Dog d : doggies ) {
  agesSoFar = agesSoFar +1 d.getAge();
  }
This is a great for-each loop; Java contrives to set d to be a different Dog, each time through the loop.

But it turns out, before Java 1.5, the Java language had while loops, but no for-each loop! How on earth did programmers add up the ages in a list-of-Dogs? Well, a while loop can suffice, but we need to get d to refer to a different Dog each time through the loop?

// A for-each loop to add all the ages of every Dog in doggies.
int agesSoFar = 0;
Dog d;
                
while (                  ) {
                  
  agesSoFar = agesSoFar + d.getAge();
                  
  }

Searching, revisited

We saw earlier that we could use for-each loops to search for an element of a list; in fact we saw multiple versions. Here's a version which looks for a happy dog in a list:

A while loops is more appropriate, since we didn't want to process every single element of the list identically. We can avoid using return as part of our loop-control logic.


1We can abbreviate agesSoFar = agesSoFar + d.getAge(); as agesSoFar += d.getAge();. We don't stress “+=” because while it is more descriptive/readable once you're used to reading the shorthand, it is also new bit of syntax (overhead to learn), and it's not that much more concise. Also, be careful not to write something like “x =+ 7; //BAD CODE; that's the same as “x = +7”!”      

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


©2008, Ian Barland, Radford University
Last modified 2008.Jan.24 (Thu)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme