CS 145 Lecture 22 – Designing objects
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
don’t know how they work
bladder, bowel, spleen, these objects
but hot dogs yummy