HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Programming a simple clock

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
programmingsimpleclock

Problem

Here's the start of some code for a clock that can display time in 24 and 12 hours.

What could be added to it? How could I can apply notions such as OOP, model and Enums here?

public Clock {
    private int time = 0;

    public int get24hrTime(){
        return time;
    }

    public int set24hrTime( int newTime ){
        this.time = newTime;
    }

    public int get12hrTime(){
        if( time - 12 < 0 ){
            return time;
        } else {
            return time - 12;
        }
    }

    public String get12hrPostfix(){
        if( hours - 12 < 0 ){
            return "AM";
        } else {
            return "PM";
        }
    }
}

Solution

Why do you check the time with (hours - 12 23 for your code to work. Why don't you check this?

Also what about the value
0 for your hours? This must be displayed as 12 AM. At the moment you return 0 in this case where it must be 12.

Also for the value
12 of the hours you return 0 as value for the 12hrTime` which is wrong.

To sum up I would suggest the following code:

public Clock {
    private int time = 0;
    public int get24hrTime() {
        return time;
    }
    public int set24hrTime(int newTime) {
        if (newTime > 23 || newTime < 0) {
            throw new IllegalArgumentException();
        }
        this.time = newTime;
    }
    public int get12hrTime(){
        if (time == 0) {
            return 12; // Special case 0
        } else if (time <= 12) {
            return time;
        } else {
            return time - 12;
        }
    }
    public String get12hrPostfix() {
        if (time < 12) {
            return "AM";
        } else {
            return "PM";
        }
    }
}

Code Snippets

public Clock {
    private int time = 0;
    public int get24hrTime() {
        return time;
    }
    public int set24hrTime(int newTime) {
        if (newTime > 23 || newTime < 0) {
            throw new IllegalArgumentException();
        }
        this.time = newTime;
    }
    public int get12hrTime(){
        if (time == 0) {
            return 12; // Special case 0
        } else if (time <= 12) {
            return time;
        } else {
            return time - 12;
        }
    }
    public String get12hrPostfix() {
        if (time < 12) {
            return "AM";
        } else {
            return "PM";
        }
    }
}

Context

StackExchange Code Review Q#29392, answer score: 6

Revisions (0)

No revisions yet.