0

这是我的秒表课。我的问题是,我怎样才能将它转换为秒,以便它在几秒钟内给我输出?提前致谢

public class StopWatch

{  
   /**
      Constructs a stopwatch that is in the stopped state
      and has no time accumulated.
   */
   public StopWatch()

   {  

 reset();

   }

   /**
      Starts the stopwatch. Time starts accumulating now.
   */
   public void start()

   {  

      if (isRunning) return;

      isRunning = true;

      startTime = System.currentTimeMillis();

   }

   /**
      Stops the stopwatch. Time stops accumulating and is
      is added to the elapsed time.
   */
   public void stop()

   {  

      if (!isRunning) return;

      isRunning = false;

      long endTime = System.currentTimeMillis();

      elapsedTime = elapsedTime + endTime - startTime;

   }

   /**
      Returns the total elapsed time.
      @return the total elapsed time
   */
   public long getElapsedTime()

   {  

      if (isRunning) 

      {  

         long endTime = System.currentTimeMillis();

         return elapsedTime + endTime - startTime;

      }

      else

         return elapsedTime;

   }

   /**
      Stops the watch and resets the elapsed time to 0.
   */
   public void reset()

   {  

      elapsedTime = 0;

      isRunning = false;

   }

   private long elapsedTime;

   private long startTime;

   private boolean isRunning;

}
4

2 回答 2

1

您可以使用TimeUnit枚举轻松转换时间单位。只需使用转换方法,如

//lets see how many seconds are in 1234 milliseconds 
System.out.println(TimeUnit.SECONDS.convert(1234, TimeUnit.MILLISECONDS));
//output: 1
于 2013-10-25T01:49:53.370 回答
0

使用 Google Guava 库com.google.common.base.Stopwatch类,无需重新发明轮子。

于 2013-10-25T01:53:34.217 回答