Minggu, 15 Desember 2019

Penggunaan String Java

Nama: Risky Aswi Narni
Nrp: 05111740000014
Kelas: PBO A

Penggunaan string java

 1. Membuat Class Times

public class Times
{
    public static void main(String [] Args){
     
        //membuat variabel instance
        Time time = new Time();
       
        // output string representations of the time
        System.out.print ("The initial universal time is: ");
        System.out.println (time.toUniversalString());
        System.out.print ("The initial standard time is: ");
        System.out.println (time.toString());
        System.out.println(); // output a blank line
       
        // change time and output updated time
        time.setTime (13, 27, 6);
        System.out.print ("Universal time after setTime is: ");
        System.out.println (time.toUniversalString());
        System.out.print ("Standard time after setTime is: ");
        System.out.println (time.toString());
        System.out.println(); // output a blank line
       
        // attempt to set time with invalid values
        try
        {
            time.setTime (99, 99, 99); // all values out of range
        } // end try
        catch (IllegalArgumentException e)
        {
            System.out.printf ("Exception: %s\n\n", e.getMessage());
        } // end catch
       
        // display time after attempt to set invalid values
        System.out.println ("After attempting invalid settings:" );
        System.out.print ("Universal time: ");
        System.out.println (time.toUniversalString());
        System.out.print ("Standard time: ");
        System.out.println (time.toString());
   
    }
}
2. Membuat Class Time
  
 public class Time
{
    private int hour; // 0 - 23
    private int minute; // 0 - 59
    private int second; // 0 - 59
   
    Time(){
    }    
   
    // set a new time value using universal time; throw an
    // exception if the hour, minute or second is invalid.
    public void setTime (int h, int m, int s)
    {
        // validate hour, minute and second
        if ((h >= 0 && h < 24) && ( m >= 0 && m < 60) && (s >= 0 && s < 60))
        {
            hour = h;
            minute = m;
            second = s;
        } // end if
        else
        {
            throw new IllegalArgumentException
            ("hour, minute and/or second was out of range");
        }
    } // end method setTime
   
    // convert to String in universal-time format (HH:MM:SS)
    public String toUniversalString()
    {
        return String.format ("%02d:%02d:%02d", hour, minute, second);
    } // end method toUniversalString
   
    // convert to String in standard-time format (H:MM:SS AM or PM)
    public String toString()
    {
        return String.format ("%d:%02d:%02d %s",
            (( hour == 0 || hour == 12 ) ? 12 : hour % 12),
            minute, second, (hour < 12 ? "AM" : "PM"));
    } // end method toString
}
3. Hasil/ output

Tidak ada komentar:

Posting Komentar