集册 Java实例教程 类声明将时间保持在24

类声明将时间保持在24

欢马劈雪     最近更新时间:2020-01-02 10:19:05

774
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
类声明以24小时制保留时间

public class Main /**来 自 时 代 J a v a - nowjava.com**/

{

   public static void main(String[] args)

   {

      // create and initialize a Time1 object

      Time1 time = new Time1(); // invokes Time1 constructor


      // output string representations of the time

      displayTime("After time object is created", time);

      System.out.println(); 


      // change time and output updated time 

      time.setTime(13, 27, 6); //时 代 J a v a - N o w J a v a . c o m 提 供

      displayTime("After calling setTime", time);

      System.out.println(); 


      // attempt to set time with invalid values

      try

      {

         time.setTime(99, 99, 99); // all values out of range

      } 

      catch (IllegalArgumentException e)

      {

         System.out.printf("Exception: %s%n%n", e.getMessage());

      } 


      // display time after attempt to set invalid values

      displayTime("After calling setTime with invalid values", time);

   } 


   // displays a Time1 object in 24-hour and 12-hour formats

   private static void displayTime(String header, Time1 t)

   {

      System.out.printf("%s%nUniversal time: %s%nStandard time: %s%n",

         header, t.toUniversalString(), t.toString());

   } 

}

class Time1  

{

   private int hour; // 0 - 23

   private int minute; // 0 - 59

   private int second; // 0 - 59


   public void setTime(int hour, int minute, int second)

   {

      // validate hour, minute and second

      if (hour < 0 || hour >= 24 || minute < 0 || minute >= 60 || 

         second < 0 || second >= 60) 

      {

         throw new IllegalArgumentException(

            "hour, minute and/or second was out of range");

      }


      this.hour = hour;

      this.minute = minute;

      this.second = second;

   } 


   // convert to String in universal-time format (HH:MM:SS)

   public String toUniversalString()

  
展开阅读全文