Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * AP CS MOOC
- * Term 2 - Assignment 1: Time
- * A class which represents the time of day in hours and seconds.
- */
- public class Time
- {
- private int hour;
- private int minute;
- /* Complete required constructors and methods here */
- /*
- *Default constructor that sets time to 0000.
- */
- public Time()
- {
- hour = 0;
- minute = 0;
- }
- /*
- * If h is between 1 and 23 inclusive, set the hour to h.
- * Otherwise, set the hour to 0. If m is between 0 and 59 inclusive,
- * set the minutes to m. Otherwise, set the minutes to 0.
- */
- public Time(int h, int m)
- {
- if (h >= 1 && h <= 23)
- hour = h;
- else
- hour = 0;
- if (m >= 0 && m <= 59)
- minute = m;
- else
- m = 0;
- }
- /* Returns the time as a String of length 4 in the format: 0819.
- * Notice that if the hour or minute is one digit, it should
- * print a zero first. For example, 6 should print as 06.
- */
- public String toString()
- {
- if (hour/10 == 0)
- System.out.print("0" + hour);
- else
- System.out.print(hour);
- if (minute/10 == 0)
- System.out.print("0" + minute);
- else
- System.out.print(minute);
- return "";
- }
- /*
- * Returns the time as a String converted from military time
- * to standard time. For example, 0545 becomes 5:45 AM and
- * 1306 becomes 1:06 PM.
- */
- public String convert()
- {
- int flag = 0;
- int f2 = 0;
- int h = hour;
- if (hour > 12)
- {
- h -= 12;
- flag = 1;
- }
- else if (hour == 0)
- h = 12;
- if (minute/10 == 0)
- f2 = 1;
- if (f2 == 0)
- System.out.print(h + ":" + minute + " ");
- else
- System.out.print(h + ":0" + minute + " ");
- if (flag == 1)
- System.out.print("PM");
- else
- System.out.print("AM");
- return "";
- }
- /*
- * Advances the time by one minute.
- * Remember that 60 minutes = 1 hour.
- * Therefore, if your time was 0359, and you add one minute,
- * it becomes 0400. 2359 should increment to 0000.
- */
- public void increment()
- {
- if (minute < 59)
- minute++;
- else
- {
- if (hour < 23)
- hour++;
- else
- hour = 0;
- minute = 0;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement