CS 2102 (B10): Object-Oriented Design Concepts
On For-Loops


Figuring out how to write for-loops over lists is easier if you appreciate the high-level structure of the computation. In the following code skeleton, substitute single expressions for terms in all-caps, and substitute computations for descriptions in square-brackets:

  RETURN-TYPE result;  // a local variable (field) in the class

  result = [the result when the list is empty]
  for ( TYPE VARNAME : SPECIFIC-LIST ) {
    result = [expression to build new result from current
              value of result and VARNAME];
  }
  return result;

For example, to sum up a list of numbers, we would write

int sum (LinkedList<Integer> numList) {
  int result;

  result = 0;
  for ( Integer n : numList ) {
    result = result + n;
  }
  return result;
}
  

Study this pattern and try it out on the following examples. The examples are for a list of Songs, where a song has an artist, title, and price (feel free to use an int for the price).

  1. Write a method numCheap that consumes a LinkedList and produces an integer indicating how many songs cost less than two dollars.

  2. Write a method discount that consumes a LinkedList and produces a LinkedList in which each song is discounted by 10%. Do this without modifying the individual songs.

  3. Repeat the previous problem, this time changing the price in the song classes in the original list.

  4. Write a method discography that consumes a LinkedList and an artist (String) and produces a LinkedList with all songs by that artist.

Feel free to see us in office hours or ask on the board if you have questions on any of these.