第九章第六题(秒表)(Stopwatch)

第九章第六题(秒表)(Stopwatch)

  • *9.6(秒表)设计一个名为StopWatch的类,该类包含:

    • 具有设置方法的私有数据与startTime和endTime。
    • 一个无参构造方法,使用当前时间来初始化startTime。
    • 一个名为start()的方法,将startTime重设为当前时间。
    • 一个名为stop()的方法,将endTime设置为当前时间。
    • 一个名为getElapsedTime()的方法,返回以毫秒为单位的秒表记录的流逝时间。

    画出该类的YML图并实现这个类。编写一个测试程序,用于测量使用选择排序对100000个数字进行排序的执行时间。
    *9.6(Stopwatch)Design a class named stopwatch, which contains:

    • Private data with setting method and starttime and Endtime.
    • A nonparametric constructor that initializes starttime with the current time.
    • A method called start() resets starttime to the current time.
    • A method called stop() sets Endtime to the current time.
    • A method called getelapsedtime() returns the elapsed time recorded by the stopwatch in milliseconds.

    Draw the YML diagram of the class and implement the class. Write a test program to measure the execution time of sorting 100000 numbers using selective sorting.

  • 参考代码:

package chapter09;

public class Code_06 {
    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 void setStartTime(long newStartTime){
        startTime = newStartTime;
    }
    public void setEndTime(long newEndTime){
        endTime = newEndTime;
    }
    public StopWatch(){
        startTime = System.currentTimeMillis();
    }

    public void start(){
        startTime = System.currentTimeMillis();
    }

    public void stop(){
        endTime = System.currentTimeMillis();
    }

    public long getElapsedTime(){
        return endTime - startTime;
    }
}

  • 结果显示:
7477

Process finished with exit code 0

  • 11
    点赞
  • 85
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值