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

homeinfoarchiveexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lect12a
while loops

a segue

Exercise: Complete the following, using a for-each loop:

/** Return the number of Widgets in a list-of-Widgets.
 *  Our method will work even if the List method "size()" is broken/missing.
 * @param things The list of items to count.
 * @return the number of Widgets in `things`.
 */
public static int mySize( java.util.LinkedList<Widgets> things ) {




  }
Hint: What information will you accumulate, as you look at more and more items?
  1. How to represent that information? Declare a “so-far” variable to hold that info!
    (Its type will be the same type as the answer you're trying to compute, almost always.)
  2. What will the value of that “so-far” variable be, before even you've looked at a single item in the list?
  3. Use a for-each loop to set up the loop's index variable.
  4. When you're halfway through the list, how will you update your idea of the “so-far” information, in the light of the next object you are currently looking at?
This problem is almost too easy, because it doesn't care at all about the details of the Widget it's looking at.

In our solution, our “so-far” variable is just tracking how many items we've already seen (processed). Note that this is the same as tracking the index of the item we'll look at next.

Over the next week, we'll look at two other types of loops — while loops and for loops (as opposed to for-each loops); we will routinely keep track of such an index manually, in addition to any other information we accumulate.

While

Here is the source code for this week's lectures: lect12-loop-practice, lect12-loop-practice.jar. (how-to-get-jar-files-into-BlueJ—Downloading .jar files into BlueJ)

For-each loops are nice when we have a list to process (and, we want to handle each element in exactly the same way). But what about when we want to do something over-and-over, but we don't have a list? For example: We want to play a game of volleyball -- keep playing a single point, until the game is over. Recall/review the methods we wrote back in hw03soln-VolleyballJudge.html.

  /** Play one game of volleyball, and say which team one.
   * @return Whether or not the first team won.
   */
  public boolean playOneGame() {
    int score1 = 0;
    int score2 = 0;

    while (! this.isGameOver(score1,score2) ) {
      // ...play one point...
      }

    // When we reach this line, we know the game is over -- *somebody* has won!
    return this.hasFirstTeamWon(score1,score2);
    }
That's the skeleton use of the while-loop. Here's the same method, but with the body filled in. Note that it uses a new class -- java.util.Random -- to generate random numbers for us:
class VolleyballJudge {
  // A field:
  private java.util.Random randNumGenerator = new java.util.Random();


  /** Play one game of volleyball, and say which team one.
   * @return Whether or not the first team won.
   */
  public boolean playOneGame() {
    int score1 = 0;
    int score2 = 0;

    while (! this.isGameOver(score1,score2) ) {
      // Play one point:
      // Choose a random team to get a point, with 50/50 odds:
      if (randNumGenerator.nextDouble() < 0.50) {
        score1 = score1 + 1;
        }
      else {
        score2 = score2 + 1;
        }
      }

    // When we reach this line, we know the game is over -- *somebody* has won!
    return this.hasFirstTeamWon(score1,score2);
    }

Another example of a while loop:
We saw earler, that if we have a source of characters (like the keyboard), we can make a java.util.Scanner who can take those individual characters and turn them into numbers (ints or doubles) or strings for us, with the method nextInt(), nextDouble(), next() (which returns the next word, as a string). There are other useful Scanner methods: nextLine() which returns the entire next line (a String), as well as a boolean method hasNext(), which determines whether the source of characters has run dry.

  /** Open up a URL, and read the input.
   * As a side-effect (for demonstration only), print each line to the console.
   * @return The number of lines in a given URL.
   */
  public static int countLines() throws java.net.MalformedURLException, java.io.IOException {
    String sourcePage = "http://www.radford.edu/itec120/2008spring/";

    // Open sourcePage for input: (Create a URL object based on sourcePage, open that URL as a stream-of-characters,
    //                             and create a Scanner who will group that stream's characters into Strings etc.)
    java.util.Scanner src = new java.util.Scanner( new java.net.URL( sourcePage ).openStream() );

    int linesSoFar = 0;      // Keep track of how many lines we've seen.

    while ( src.hasNext() ) {
      src.nextLine();   // Have the scanner consume the next line.  We ignore its return value.
      linesSoFar = linesSoFar + 1;
      }

    return linesSoFar;
    }
Task: modify this method so that it returns a single String containing the entire contents of the file.

The syntax of a while loop is what you'd expect from the above example:


When writing a while-loop, keep the same things in mind as when writing a for-each loop. However, we have a couple of new steps, because the for-each had managed our index variable for us; now we need to do that ourselves:

What does the following method return?

/** Announce a countdown, starting at 10.
 * @return A countdown starting at 10.  
 *   That is, "10...9...8... [etc] 2...1...Liftoff!"
 */
public String countdown() {
  String chantSoFar = "";  /* A local variable, to accumulate the answer. */
  int t = 10;         /* The next number to count down. */

  while (t >= 0) {
    chantSoFar = chantSoFar + (t + "...");
    t = t-1;
    }

  return (chantSoFar + "Liftoff!");
  }
In order to walk through this, we need to keep track of what chant and t are, in the environment.

homeinfoarchiveexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


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