Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Clock {
- // Fields of the class
- int hours;
- int minutes;
- // Default constructor
- Clock() {
- this.hours = 0;
- this.minutes = 0;
- }
- // Constructor with 1 argument
- Clock(int h) {
- setTime(h, 0);
- }
- // Constructor with 2 argument
- Clock(int h, int m) {
- setTime(h, m);
- }
- // Instance methods
- int getHour() {
- return this.hours;
- }
- int getMinute() {
- return this.minutes;
- }
- void incrementTimer() {
- if (this.minutes < 59) {
- this.minutes += 1;
- }
- else {
- this.minutes += 1;
- this.hours += 1;
- this.minutes = 0;
- }
- }
- void incrementTimer(int x) {
- for (int i = 0; i < x; i++) {
- incrementTimer();
- }
- }
- void setTime(int h, int m) {
- if ((h >= 0 && h <= 24) && (m >= 0 && m <= 59)) {
- this.hours = h;
- this.minutes = m;
- }
- else if ((h > 24 || m > 60)||(h > 24 && m > 60)) {
- System.out.println("Invalid Input");
- }
- }
- public String toString() {
- String hs = String.valueOf(hours);
- String ms = String.valueOf(minutes);
- String time = "";
- String sm = ":";
- if(hs.length() == 1) {
- hs = "12";
- }
- if(hs.length() == 1) {
- hs = "0" + hs;
- }
- if(minutes <= 9) {
- ms = "0" + ms;
- }
- if(hours < 12) {
- time = " AM";
- }
- else {
- time = " PM";
- }
- if(hours > 12 && hours < 21) {
- hs = "0"+ String.valueOf(hours-12);
- }
- else if (hours > 24){
- hs = String.valueOf(hours-12);
- }
- return hs + sm + ms + time;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment