teaching machines

CS 145 Lecture 22 – Stopwatch

April 25, 2012 by . Filed under cs145, lectures, spring 2012.

Agenda

Code

NDeckerBurger.java

package prefinal;

public class NDeckerBurger {
  private int nDecks;
  private boolean hasCheese;
  
  public static final int CALORIES_PER_DECK = 211;
  
  public NDeckerBurger(int givenDeckCount) {
    nDecks = givenDeckCount;
  }
  
  public NDeckerBurger(int givenDeckCount, boolean hasCheese) {
    nDecks = givenDeckCount;
    this.hasCheese = hasCheese;
  }
  
  public int getDeckCount() {
    return nDecks;
  }
  
  public int getPickleCount() {
    return 3 * nDecks;
  }
  
  public int getCheeseCount() {
    if (hasCheese) {
      return 1 * nDecks;
    } else {
      return 0;
    }
  }
  
  public int getBunCount() {
    return nDecks + 1;
  }
  
  public int getKetchupOunces() {
    return nDecks;
  }
  
  public int getBaconCount() {
    return 3 * nDecks;
  }
  
  public void fuse(NDeckerBurger other) {
    nDecks += other.nDecks;
    if (other.hasCheese) {
      hasCheese = true;
    }
  }
  
  public double getCalorieCount() {
    return CALORIES_PER_DECK * getDeckCount() +
        31 * getCheeseCount() + 
        10 * getPickleCount() +
        27 * getBunCount() +
        41 * getBaconCount() +
        10 * getKetchupOunces() / 0.4;
  }
}

Stopwatch.java

package prefinal;

import java.util.Scanner;

public class Stopwatch {
  private long startTime;
  private long endTime;
  
  private boolean hasStarted;
  private double seconds;
  
  public Stopwatch() {
    seconds = endTime - startTime;
    hasStarted = false;
    seconds = 0.0;
  }

  public void start() {
    startTime = System.currentTimeMillis();
    hasStarted = true;
  }
  
  public void stop() {
    endTime = System.currentTimeMillis();
    hasStarted = false;
  }

  /**
   * Resets the stopwatch. If running, it continues running.
   */
  public void reset() {
    startTime = endTime = System.currentTimeMillis();
    
//    endTime = System.currentTimeMillis();
//    startTime = endTime;
    
    seconds = 0.0;
  }
  
  public double getElapsedSeconds() {
    seconds = (endTime - startTime) / 1000.0;
    return seconds;
  }
  
  public static void main(String[] args) {
//    System.out.println(System.currentTimeMillis());
    
    Stopwatch ticker = new Stopwatch();
    
    String zyx = "zyxwvutsrqponmlkjihgfedcba";
    Scanner in = new Scanner(System.in);
    System.out.print("Hit Enter when ready");
    in.nextLine();
    
    ticker.start();
    String line = in.nextLine();
    ticker.stop();

    boolean isMatch = zyx.equals(line);
    
    if (isMatch) {
      System.out.println(ticker.getElapsedSeconds());
    } else {
      System.out.println("Sorry.");
    }
  }
}

Haiku

My game didn’t sell.
hitPoints was a static field.
If one died, all died.