teaching machines

CS 145 Lecture 32 – Objects Cont’d

November 30, 2016 by . Filed under cs145, fall 2016, lectures.

Dear students,

In object-oriented programming, the programmer is really a writer of screenplays. Objects are our actors, which we orchestrate around the stage. We cue them to say certain things, have them interact with other objects, and shape them to have an identity that is all their own.

Today, we’ll feel our away around the identities of several objects through some blackboxes. Once we get an idea for what they do, we will implement them in Java.

Blackbox #1
Blackbox #2
Blackbox #3
Blackbox #4
Blackbox #5
Blackbox #6

Here’s your TODO to complete before we meet again:

See you next class!

Sincerely,

P.S. Here’s the code we wrote together…

AltStar.java

package lecture1130;

public class AltStar {
  private boolean isSingle;
  
  public AltStar() {
    isSingle = true;
  }

  public String starify() {
    boolean wasSingle = isSingle;
    isSingle = !isSingle;
    if (wasSingle) {
      return "*";
    } else {
      return "**";
    }
  }
}

AltStarTest.java

package lecture1130;

public class AltStarTest {
  public static void main(String[] args) {
    AltStar twinkler = new AltStar();
    for (int i = 0; i < 30; ++i) {
      System.out.println(twinkler.starify());
    }
  }
}

Counter.java

package lecture1130;

public class Counter {
  private int maxValue;
  private int i;
  
  public Counter(int maxValue) {
    i = 0;
//    reset();
    this.maxValue = maxValue;
  }
  
  public boolean tick() {
    i++;
    return i >= maxValue;
  }
  
  public void reset() {
    i = 0;
  }
}

CounterTest.java

package lecture1130;

public class CounterTest {
  public static void main(String[] args) {
    Counter counter = new Counter(1);
    System.out.println(counter.tick());
  }
}

Raffle.java

package lecture1130;

import java.util.ArrayList;
import java.util.Random;

public class Raffle {
  private ArrayList<String> names;
  
  public Raffle() {
    names = new ArrayList<String>();
  }
  
  public void add(String name) {
    add(name, 1);
  }
  
  public void add(String name,
                  int n) {
    for (int i = 0; i < n; ++i) {
      names.add(name);
    }
  }
  
  public String draw() {
    Random privilegeBuster = new Random();
    int i = privilegeBuster.nextInt(names.size());
    String name = names.remove(i);
    return name;
  }
  
  public static void main(String[] args) {
    Raffle raffle = new Raffle();
    raffle.add("Hannah");
    
    raffle.add("Brad");
    raffle.add("Brian");
    raffle.add("Brendan");
    raffle.add("Kyler");
    raffle.add("Jaden");
    raffle.add("Parker");
    raffle.add("Chris");
    raffle.add("Kevin");
    raffle.add("Kalia");
    raffle.add("Amanda");
    raffle.add("Vince");
    System.out.println(raffle.draw());
  }
}