teaching machines

CS 145 Lecture 17 – Arrays

November 7, 2011 by . Filed under cs145, fall 2011, lectures.

Agenda

Code

Fill.java

package lecture;

public class Fill {
  public static void main(String[] args) {
    double[] series = fill(12, 54, 10);
    for (int i = 0; i < series.length; ++i) {
      System.out.println(series[i]);
    }
  }

  /**
   * Create a list of length items, whose first item is first, whose second item
   * is second, and whose remaining elements ...
   * 
   * @param first First value
   * @param second Second value
   * @param length Number of items in list
   * @return List of items following specified pattern
   */
  public static double[] fill(double first,
                              double second,
                              int length) {

    double diff = second - first;
    double[] nums = new double[length];
    
    for (int i = 0; i < length; ++i) {
      nums[i] = first + i * diff;
    }
    
    return nums;
  }
}

Raffle.java

package lecture;

import java.util.Random;
import java.util.Scanner;

public class Raffle {
  public static void main(String[] args) {
    
    String[] names = new String[10];
    int i = 0;
    
    Scanner in = new Scanner(System.in);
    System.out.print("> ");
    while (in.hasNextLine() && i < 10) {
      names[i] = in.nextLine();
      ++i;
      System.out.print("> ");
    }
    
    Random generator = new Random();
    int iWinner = generator.nextInt(i);
    System.out.println(names[iWinner]);
  }
}

TODO

Haiku

so cute, Lu and Ray
then Lu just stopped coming ’round
conditional love