Java语言程序设计|Java语言程序 例题9.6(秒表)

*9.6 (Stopwatch) Design a class named StopWatch. The class contains:
■ Private data fields startTime and endTime with getter methods.
■ A no-arg constructor that initializes startTime with the current time.
■ A method named start() that resets the startTime to the current time.
【Java语言程序设计|Java语言程序 例题9.6(秒表)】 ■ A method named stop() that sets the endTime to the current time.
■ A method named getElapsedTime() that returns the elapsed time for the
stopwatch in milliseconds.
Draw the UML diagram for the class and then implement the class. Write a test
program that measures the execution time of sorting 100,000 numbers using
selection sort.
9.6(秒表)设计一个名为Stopwatch的类。该类包含:
■ 使用getter方法的private数据字段startTime和endTime。
■ 使用当前时间初始化startTime的无参数构造函数。
■ 将startTime重置为当前时间的名为start()的方法。
■ 将endTime设置为当前时间的名为stop()的方法。
■ 一个名为getElapsedTime()的方法,该方法返回秒表(毫秒)。
绘制该类的UML图,然后实现该类。编写测试用于测量排序100000个数字的执行时间的程序,使用选择排序。
代码如下:

public class Unite9Test6 { public static void main(String[] args) { StopWatch time = new StopWatch(); int nums[] = new int[100000]; for(int i = 1; i <=100000; ++i) nums[i -1] = (int)((System.currentTimeMillis() / i) % 1000); time.start(); for(int i = 0; i <=99999; ++i)//选择排序 { for(int j = i+1; j < 100000; ++j) { if(nums[i] > nums[j]) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } } time.stop(); System.out.println(time.getElapsedTime()); } } class StopWatch { private long startTime ; private long endTime ; public long getStartTime() { return startTime; } public void setStartTime(long startTime) { this.startTime = startTime; } public long getEndTime() { return endTime; } public void setEndTime(long endTime) { this.endTime = endTime; } public void start() { startTime = System.currentTimeMillis(); //System.currentTimeMillis()用来获取当前的总毫秒数, } public void stop() { endTime = System.currentTimeMillis(); } public long getElapsedTime() { return endTime - startTime; } }

结果如下:
Java语言程序设计|Java语言程序 例题9.6(秒表)
文章图片


    推荐阅读