Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Clock {
- // Fields
- private int hours;
- private int minutes;
- private int seconds;
- // Reset method
- public void resetToMidnight() {
- hours = 0; minutes = 0; seconds = 0;
- }
- // Constructor
- public Clock(int h, int m, int s) {
- if (h<24 && h>=0 && m<60 && m>=0 && s<60 && s>=0){
- hours = h; minutes = m; seconds = s;
- } else {
- resetToMidnight();
- }
- }
- // Check if morning method
- public boolean isMorning() {
- return (hours>=5 && hours<12);
- }
- // Advance one second method
- public void tick() {
- seconds++;
- if (seconds >= 60) {
- seconds = 0;
- // need to increment mins, etc.
- minutes++;
- if (minutes>=60){
- minutes=0;
- hours++;
- hours=hours%24;
- }
- }
- }
- public String toString(){
- String hs, ms, ss;
- if (hours<10){
- hs="0"+hours;
- } else {
- hs=""+hours;
- }
- if (minutes<10){
- ms="0"+minutes;
- } else {
- ms=""+minutes;
- }
- if (seconds<10){
- ss="0"+seconds;
- } else {
- ss=""+seconds;
- }
- return hs+":"+ms+":"+ss;
- }
- public static void main(String[] args){
- Clock time1=new Clock(11, 59, 59);
- Clock time2=new Clock(56, -5, 0);
- System.out.print(time1);
- if (time1.isMorning()){
- System.out.println(" morning.");
- } else {
- System.out.println("not morning");
- }
- System.out.println(time2 + " time 2");
- time1.tick();
- System.out.print(time1);
- if (time1.isMorning()){
- System.out.println(" morning.");
- } else {
- System.out.println(" not morning");
- }
- time1.resetToMidnight();
- System.out.print(time1);
- if (time1.isMorning()){
- System.out.println(" morning.");
- } else {
- System.out.println(" not morning");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment