CS 145 Lecture 22 – Designing objects
December 2, 2011 by Chris Johnson. Filed under cs145, fall 2011, lectures.
Agenda
- writing a Stopwatch
- objects hide information
- managing a “dungeon” with objects
- writing a flashlight
Code
Stopwatch.java
package lecture;
public class Stopwatch {
/** Time at which stopwatch is started */
private long startTime;
/** Time at which stopwatch is stopped */
private long stopTime;
/**
* Starts stopwatch.
*/
public void start() {
startTime = System.currentTimeMillis();
}
/**
* Stops stopwatch.
*/
public void stop() {
stopTime = System.currentTimeMillis();
}
/**
* Gets the number of seconds elapsed between start and stop.
*
* @return Number of elapsed seconds.
*/
public double getElapsedSeconds() {
double difference = (stopTime - startTime) / 1000.0;
return difference;
}
}
AlphabetBackward.java
package lecture;
import java.util.Scanner;
public class AlphabetBackward {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Hit enter when ready.");
in.nextLine();
System.out.println("Enter alphabet backward: ");
Stopwatch timer = new Stopwatch();
// start timing here
timer.start();
String line = in.nextLine();
timer.stop();
// stop timing here
if (line.equals("zyxwvutsrqponmlkjihgfedcba")) {
System.out.println("Woo! You took " + timer.getElapsedSeconds() + " seconds.");
} else {
System.out.println("You are more forward-thinking.");
}
}
}
TODO
- Work on HW3. HW4 will be released early next week.
Haiku
the client
don’t know how they work
bladder, bowel, spleen, these objects
but hot dogs yummy
show