CS51 - Fall 2009 - Lecture 24

  • problem 13.6.2
       public int factorial( int n ){
          int result = 1;

          for( int counter = 1; counter < n; counter++ ){
             results *= counter;
          }

          return result;
       }

       - two ways to fix this

  • Write a function that given an array of integers, returns the largest number in the array
       - what does the function definition look like?
       - public int largestNumber(int[] numbers){
          int largest = numbers[0];

          for( int i = 0; i < numbers.length; i++ ){
             if( numbers[i] > largest ){
                largest = numbers[i];
             }
          }
       }
       - for loops are very natural for traversing arrays
       - note that length is a public variable not a member function
       - A very common thing that we want to do with an array is traverse all of the elements. Java provides a special for loop for this:
          - public int largestNumber(int[] numbers){
             int largest = numbers[0];

             for( int number: numbers ){
                if( number > largest ){
                   largest = number;
                }
             }
          }
       
  • show TextStat demo
       - String member method: split
          - public String[] split(String splitString);
       - We're going to write the four supporting methods to make this class
          - private String getLongestWord(String[] words)
          - private String getShortestWord(String[] words)
          - private int getNumberOfWords(String[] words)
          - private int getNumberOfCharacters(String[] words)

  • Show DrawingPanelWithShapeArray demo
       - Note how we can move things around and different objects are "in front" of other objects
       - Hard to get this behavior with recursion
       - We'll do this using arrays:
          - private DrawableInterface[] shapes = new DrawableInterface[MAX_OBJECTS];
       - How do we add a new item?
          - figure out the shape from the menu and create a new shape
          - figure out the color from the menu and set color
          - add to our shapes array