teaching machines

CS 145 Lecture 33 – Stopwatch

December 6, 2016 by . Filed under cs145, fall 2016, lectures.

Dear students,

As we saw with methods, a primary benefit of object-oriented programming is code reuse. We can create a utility and use it over and over again, in many contexts. We will do just that by designing a Stopwatch class. We will use it to time a few operations:

  1. a words-per-minute calculator
  2. the amount of time it takes to brute force crack a password
  3. a competition to type in the alphabet backward

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

See you next class!

Sincerely,

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

Stopwatch.java

package lecture1205;

public class Stopwatch {
  private long startedAt;
  private long stoppedAt;
  private boolean isRunning;

  public Stopwatch() {
    isRunning = false;
  }

  public void start() {
    startedAt = System.currentTimeMillis();
    isRunning = true;
  }

  public double stop() {
    if (!isRunning) {
      throw new BadStopwatchStateException();
    } else {
      stoppedAt = System.currentTimeMillis();
      return (stoppedAt - startedAt) / 1000.0;
    }
  }
}

BadStopwatchStateException.java

package lecture1205;

public class BadStopwatchStateException extends RuntimeException {

}

Password.java

package lecture1205;

public class Password {
  public static final String SECRET2 = "of";
  public static final String SECRET3 = "tri";
  public static final String SECRET4 = "slar";
  public static final String SECRET5 = "three";
  public static final String SECRET6 = "foobag";
  public static final String SECRET8 = "splatbot";

}

BruteForcer.java

package lecture1205;

public class BruteForcer {
  public static void main(String[] args) {
    Stopwatch timer = new Stopwatch();
    boolean foundIt = false;

    timer.start();
    for (char l1 = 'a'; !foundIt && l1 <= 'z'; ++l1) {
      for (char l2 = 'a'; !foundIt && l2 <= 'z'; ++l2) {
        for (char l3 = 'a'; !foundIt && l3 <= 'z'; ++l3) {
          for (char l4 = 'a'; !foundIt && l4 <= 'z'; ++l4) {
            for (char l5 = 'a'; !foundIt && l5 <= 'z'; ++l5) {
              for (char l6 = 'a'; !foundIt && l6 <= 'z'; ++l6) {
                for (char l7 = 'a'; !foundIt && l7 <= 'z'; ++l7) {
                  for (char l8 = 'a'; !foundIt && l8 <= 'z'; ++l8) {
                    String password = "" + l1 + l2 + l3 + l4 + l5 + l6 + l7 + l8;
                    if (Password.SECRET8.equals(password)) {
                      System.out.println(password);
                      foundIt = true;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
    double time = timer.stop();
    System.out.println(time);
  }
}