teaching machines

CS 145 Lecture 37 – This, Local, Instance, Static

December 1, 2014 by . Filed under cs145, fall 2014, lectures.

Agenda

Program This

Write a Set object. Sets are collections of values where repeats are ignored. Sets are useful for managing digital photos (where reimporting from a camera wastes resources and creates confusion), for building concordances (lists of words used in a text) and indices, and so on.

Let your Set class manage a set of Strings. Include methods for adding new elements (ignore repeats), determining the size, and accessing elements.

Code

Person.java

package lecture1201;

import java.util.Calendar;
import java.util.GregorianCalendar;

public class Person {
  private String name;
  private GregorianCalendar birthday;
  
  public Person(String name,
                int year,
                int month,
                int day) {
    this.name = name;
    this.birthday = new GregorianCalendar(year, month - 1, day);
  }
  
  public String toString() {
    return String.format("%s was born on %d/%d/%d",
                         name,
                         birthday.get(Calendar.YEAR),
                         birthday.get(Calendar.MONTH) + 1,
                         birthday.get(Calendar.DAY_OF_MONTH));
  }
  
  public static void main(String[] args) {
    Person p = new Person("Abraham Lincoln", 1809, 2, 12);
    System.out.println(p);
  }
}

Vector2D.java

package lecture1201;

public class Vector2D {
  private double x;
  private double y;
  
  public Vector2D() {
    x = y = 0.0;
  }
  
  public Vector2D(double x, double y) {
    this.x = x;
    this.y = y;
  }
  
  public double getLength() {
    return Math.hypot(x, y);
  }
  
  public void normalize() {
    x /= getLength();
    y /= getLength();
  }
  
  public String toString() {
    return String.format("%f %f -> %f", x, y, getLength());
  }
  
  public static void main(String[] args) {
    Vector2D v = new Vector2D(10, 10);
    v.normalize();
    System.out.println(v);
  }
}

Haiku

on inner knowledge:
I once liked hot dogs
Then I learned what they’re made of
Capitalism