StopWatch:One of the hallmarks of object-oriented programming is the idea of easily modeling real-world objects by creating abstract programming objects. As a simple example, consider StopWatch, which implements the following functions. After you create one object, you can use method start() to start the watch,then you can use method stop() to stop the watch. You can use method getElapsedTimeSecs() to calculate how many seconds elapsed. You also can use method getElapsedTime() to calculate how many milliseconds elapsed. The code is listed in the following:public class StopWatch {private long startTime = 0;private long stopTime = 0;private boolean running = false;public void start() {this.startTime = System.currentTimeMillis();this.running = true;}public void stop() {this.stopTime = System.currentTimeMillis();this.running = false;}//elaspsed time in millisecondspublic long getElapsedTime() {long elapsed;if (running) {elapsed = (System.currentTimeMillis() startTime);}else {elapsed = (stopTime startTime);}return elapsed;}2//elaspsed time in secondspublic long getElapsedTimeSecs() {long elapsed;if (running) {elapsed = ((System.currentTimeMillis() startTime) / 1000);}else {elapsed = ((stopTime startTime) / 1000);}return elapsed;}//sample usagepublic static void main(String[] args) {StopWatch s = new StopWatch();s.start();double z =0.0;//use scanner to get an string from keyboards.stop();System.out.println(elapsed time in milliseconds: +s.getElapsedTime());}}Add two functions to this sample code:1. First, please add several statements inside main() method to read one string from keyboard. Then type stringabc. This program will return how many milliseconds you spend on typing. $ java StopWatch abc elapsed timein milliseconds: 23992. Second, add method toString() to the StopWatch class. This method result a string, which contains the elapsed time in millisecond. In addition to that, replace the following statement in main method System.out.println(elapsed time in milliseconds: + s.getElapsedTime()); With System.out.println(elapsed time in milliseconds: + s); Whenever we refer to an object, JAVA will execute the toString method automatically. In this case, objects will be replaced by the method toString(). If we run this program, we will have $ java StopWatch abc 3 elapsed time in milliseconds: 1018 Compiling and running Java programs (reminder):1. Compile your program using the command javac filename For example: java myProgram.java If you receive errors during the compilation phase,re-edit the source code file and attempt to correct them.2. Once a file successfully compiles, execute it using the java program. For example: java MyProgram What
CSC220
[Solved] CSC 220 Lab 8-StopWatch
$25
File Name: CSC_220_Lab_8-StopWatch.zip
File Size: 216.66 KB
Only logged in customers who have purchased this product may leave a review.
Reviews
There are no reviews yet.